-
Notifications
You must be signed in to change notification settings - Fork 0
OOP
Structs Blueprint of a collection of variables.
Const An object can be instantiated as a const object. However, this means that only const declared member functions can be called. Moreover, it makes the object strictly read-only. The constructor functionality remains as is.
If const keyword gets placed in the very beginning, then it is a function returning a const (eg. const int get() {}) If const keyword gets placed right before {}, then it is a const member function.
Both can be used.
const objects are limited to access only member functions marked as const.
You can also declare a class as normal, but pass it in as const.
Friend
a non member function can access the private and protected members of a class if it is declared as a friend of that class; NOT a member of the class it is friends with
side note: sometimes, when working with friend classes, you may need to have an empty declaration of a class so that there is no run-time error
friends only work one-way; if declared, otherwise cannot be implied
Polymorphism
If pointer is of type base class and is assigned address of derived, it will only be able to access things from base class, unless its defined again in derived class and the base class function is virtual
say that foo is declared like this in Base:
Class Base {
virtual void foo {return x;}
void bar {return y;}
}
Derived derived;
Base *bptr = &derived
bptr->foo;
bptr->bar;
Because pointers of class Base can only access members of Base class, this is all allowed. However, because foo is a virtual
function, it would actually look towards the Derived class definition of foo and execute the code there. virtual
sort of makes the function smart enough to look at the derived class.
maybe the slides help: "what the virtual keyword does is to allow a member of a derived class with the same name as one in the base class to be appropriately called from a pointer, and more precisely when the type of the pointer is a pointer to the base class that is pointing to an object of the derived class"
Operator Overloading
This is how to overload an operator inside a class:
Circle operator+(const Circle& C){
Circle C1;
C1.x = this->x + C.x;
C1.y = this->y + C.y;
return C1;}
When you want to call it in main, there's two ways to do it:
int main() {
Circle C3;
C3 = C1 + C2
OR
C3 = C1.operator+(C2)