Object Oriented Programming¶
some types of oop to look at¶
- object oriented modular programming
- incremental programming
notes¶
- applying
encapsulation
will lead toAbstraction
[2]. - in c++: class is a
structure
that all its members are private by default [2]. -
summary about entity access control types in classes:
Entity type Inhereted ? accessed by class methods ? accessed outside the class ? eg. setters and getters eg. directly as className.entity private - - - protected + + - public + + +
intro¶
- structures (classes) is a collection of variables of possibly different types.
- an object is in instance of the structure, we can call it a structure itself.
- structures can be memberes of another structures
-
you
can't
thesame
structure type as member of thesame
type, because we will get infinite loop of memory reservations.// c++ struct MyStruct { int x; MyStruct y; // this is wrong }
Structures and pointers¶
-
structures in memory:
![pointers in em]
-
myStruct*
is pointer to MyStruct type. -
Example:
// c++ struct MyStruct { int x; int y; } MyStrcut p1; // defining a new object MyStruct* ptr // define a variable of type pointer to mystruct ptr = &p1 // assign memory addres of p1 to ptr *ptr = { 1 , 2 } // assign the data in memory addres &p1 to {1,2} // to access the pointer of y of p1 ptrY = &p1 + 4 // &p1 points to the first member of p1 whic is x, x takes 4 bytes, after 4 byets we reach y. // OR ptr->y = 2 // assign data in y pointer to 2 // (&p1)->y = 2
-
pointers in structures:
in the photo above, istead of reserving
extra 54 bytes
for the driver in t1 we are pointing to d1 which cost only 4 bytes. -
since we
can not
use a structure as member of the same structure type, we can use its pointer in our code as this:in this photo,
t2.next
points tot1
, although t1 and t2 are from the same type, wecan't
use t1 as member of t2, but wecan
point to it. -
writting to the
heap
starts with the wordnew
, asint* ptr = new int
// c++ struct MyStruct { int x; int y; } MyStruct* p1 = new MyStruct // we are writting to the heap // (dynamically allocating memory for the new struct) // now can dynamically handle p1 contents
concepts¶
- entites: all members of class.
- abstraction: hide the un-necesary details of the class.
- entites can be [1]:
- fixed (like methods)
don't change
while the object interacts. - state (like vars)
change
while the object interacts.
- fixed (like methods)
member functions¶
- member functions are the methods of a class.
- member functions are fixed entries [1].
-
calling member functions.
className.classFnc(funcArg) // className is the reciever // claassFunc is the member function // funcArg arguments that are passed to the method
-
interfaces: simple layer hiding everything (eg. member function with no arguments)
Access control of members in structures¶
- Crucial for data hiding or encapsulation [2].
public¶
- Member can be accessed from anywhere in program
- can be inhereted.
private¶
- Member can be accessed only from member functions of same
structure (class)
. - reading and writting can be done only using the class methods
setters and getters
. - make sure that these getters and setters are public so they can be accessesd by other parts of the program.
can not
be inhereted.
protected¶
- moderate private.
- can be accessed only in the defintion of the derived classes.
Mutator functions¶
- Member functions that update values of data members that other functions are allowed to update [3].
Constructor¶
- Invoked automatically when an object of the class is allocated [3].
- Convenient way to initialize
data members
. - Just like any other member function
- Accepts optional input parameters
- Can be used to perform tasks other than initialization too [3].
- class can have multiple constructors as long as each one has a distinct list of parameter types.
- When allocating an object of the class, the types of parameters passed to the constructor determine which constructor is invoked.
-
constructors must be public [3].
calss V3 { double x, y, z; // first constructor: normal. V3(double a, double b, double c){ x = a; y = b; z = c; return; } // second constructor: initialazation, no parameters. // default constructor V3(){ x=y=z=0.0; return; } // third constructor : with default values, some params are optional V3(double a = 0.0 , double b = 1.0, double c = 2.0){ x = a; y = b; z = c; return; } // destructor ~V3() { if (length() == 0.0) { cout << “Zero vector!!!”; return; } } V3 myObj1; // invoke second constructor V3 *myObj2 = new V3(1.0, 2.0. 3.0); // invokes first constuctor V3 *myObj2 = new V3(1.0, 2.0); // invokes third constuctor
Default constructor¶
- a constructor method without any params.
-
when you define an array of type
MyClass
:- the default constructor, the one without parameters, will be invoked when you intialize a new class without specyfying a constructr [3].
- if no default constructor the compiler will provide one for you, but it might not be as you want [3].
- If a non-default constructor is defined, but not a default constructor, C++ compiler will NOT provide a
bare-bones
default constructor, and the array will not defined, get anError
.
-
Best practice:
Always
Define default constructors.
copy constructor¶
- constructor method that take a class as parameter, and return a new class from the same type.
-
the parameter class should be passed by
reference
, so the old class values will be copied to the new class.class V3 { int x,y,z; V3 copyConstrutor ( const V3 &objFromSameClass){ V3 v; v.x = objFromSameClass.x v.y = objFromSameClass.y v.z = objFromSameClass.z return v; } // another Example here: https://i.imgur.com/UfiJgY2.png }
Destructor¶
- Invoked automatically when an object of the class is de-allocated.
- Convenient way to do book-keeping/cleaning-up before deallocating object [3].
- Accepts no parameters.
- Can be used to perform other tasks before de-allocating object [3].
- must be public.
operator overloading¶
-
create a special functions to be invoked after some operetors (eg: + - * /) [4].
class V3 { private: double x, y, z; public: // operator + overloading V3 operator+ (const V3 &b) { return V3(x + b.x, y + b.y, z + b.z); } // operator * overloading V3 operator* (const double factor) { return V3(x*factor, y*factor, z*factor); } }; // in main v1 = new V3(1.0,2.0,3.0) v2 = new V3(4.0,5.0,6.0) v4 = v1 * v2 // this will execute the function with the operator loading.
Assignment Overloading¶
- We can re-define the assignment operator for a class/struct by defining the member function operator= [4].
Friend classes and functions¶
- A “friend” declaration allows a class to explicitly allow specific non-member functions to access its private members.
- a function can be friend to several classess.
- a class can be friends with several functions.
-
in the class defenetion I declare:
```c++ // c++ class V3 { // code friend ReturnType FuncName( …Params ); // this will give the FuncName Access to private properties of the class V3
// OR friend class ClassName; // all functions of className will be friends with V3.
}
static data members¶
- members of class that will share its value with all objects of the class [4].
- if this
static data
changed in one object, it will change with all other objects of this class [4].
Inheritance¶
- when there are some common features between mutliple classes, we can use a base class contains the common properties. then we
extend
each class with its own properties.
Compositional Way¶
- the inhereted class cotains one property of the type
base class
. - we need to access our new class, then the base class to get access to its properties.
Inheritance Way¶
-
the new class extends the previous one, so we can access the propieties of the base class directly as if they were a properties to the extended class.
copmaring composional way to inhertance way.
-
example of Bank accouts heirachy, where you need to use inheretance: https://i.imgur.com/XiXsPcR.png [4].
Access Control in Derived Classes¶
- the base class is the class that contains the common properties.
- the derived class is the new class that extends the base one.
- the propereties types in base class can be: 1.public 2.private 3.protected.
- the type of derivation (inhertenace) can also be: 1.public 2.private 3.protected.
- the comination of propert type and inhertenace type can control the accessebilty of the base property in the derived class.
- From both types, the one with more privacy and less accessbility will be dominated as :
private > protected > public
. -
summary of the inheretance depending on both types [4]:
Methods Inheretance¶
- methods can be redefined in the derived class.
-
to call the method of the base (super) class after you redefine you can do:
c++ class savings : public base { public: int age; long int ATM; void printInfo() { base::printInfo() // when call savings.printInfo() will execute the both methods from base and savings. cout << "\nPrinting in savings: \n"; cout << age << ", " << ATM << endl; } };
-
instantianting a new derived class will call both constructors of
the default constructor of the base
then the constructor of the derived class. - if the base class doesn’t have default construcor (eg. its constructor has arguments) you need to explicitly call the base constructor when constructing the derived class.
polymorphism¶
- a derived class can be used as its
shape
or asbase class
because it has all data in the base class. - so, we have 2 shapes or forms of the derived class, that’s polymorphism.
- inhereted methods that are redefined in the derived class can be used as its original defention or its second defenition, this is also polymorphism.
- example here: https://i.imgur.com/d6Wz17A.png
virtual functions¶
- implements polymorphism in the function calls.
- functions defined in the base class, but they need to be redefined in the dervied class in order to work.
- example here: https://i.imgur.com/DPbIAqe.png
Abstract class¶
- A class that cannot be instantiated directly.
- instantiation of this class will give compiler error.
- Implemented as a class that has one or more
pure virtual functions As. virtual void FuncName() = 0;
Which should be overridden by member function definitions of derived class. - used when using the base class has no meaningfull meaning.
- Example (Bank account):
- A person does not have just a bank account.
- It is either a savings bank account or a current bank account
- Instantiating class ‘base’ by itself has no meaningful purpose