Object Oriented Programming Inharitance
Object Oriented Programming Inharitance
PROGRAMMING
(OOP)
INHERITANCE IN CLASSES
IS
A relationship is modeled with the help of
public inheritance
Syntax
class ChildClass
: public BaseClass{
...
};
EXAMPLE
class Person{
...
};
class Student: public Person{
...
};
ACCESSING MEMBERS
base member1
base member2 Data members of
... base class
derived member1 Data members of
derived member2 derived class
...
ALLOCATION IN MEMORY
int main(){
Child cobj;
return 0;
}
Output:
Parent Constructor...
Child Constructor...
CONSTRUCTOR
class Parent{
public:
Parent(int i){…};
};
class Child : public Parent{
public:
Child(int i): Parent(i)
{…}
};
EXAMPLE
class Parent{
public:
Parent(){cout <<
“Parent Constructor...”;}
...
};
class Child : public Parent{
public:
Child():Parent()
{cout << “Child Constructor...”;}
...
};
BASE CLASS INITIALIZER
class Parent{
public:
Parent(){…}
};
class Child : public Parent{
int member;
public:
Child():member(0), Parent()
{…}
};
BASE CLASS INITIALIZER
class Person{
public:
int age;
char *name;
...
public:
Person();
};
EXAMPLE
class Parent{
public:
Parent(){cout <<“Parent Constructor”;}
~Parent(){cout<<“Parent Destructor”;}
};
Output:
Parent Constructor
Child Constructor
Child Destructor
Parent Destructor