12 constructors invocation and data members initialization
1. 09/04/131 VIT - SCSE
• In multiple inheritance, the constructors of base classes
are invoked first, in order in which they appear in the
declaration of the derived class.
• In multilevel inheritance, they are executed in the order of
inheritance.
• Data member initialization is represented by
• Datamembername(value)
• The value can be arguments of a constructor, expression
or other data members.
Constructors Invocation and Data Members Initialization
2. 09/04/132 VIT - SCSE
class B
{
protected:
int x,y;
public:
B(int a,int b):x(a),y(b) //x=a, y=b
{
}
};
class D:public B
{
private:
int a,b;
public:
D(int p,int q,int r):a(p),B(p,q),b(r)
{
}
void output()
{
cout<<”x=”<<x<<endl;
cout<<”y=”<<y<<endl;
cout<<”a=”<<a<<endl;
cout<<”b=”<<b<<endl;
}
};
void main()
{
D ob(5,10,15);
ob.output();
}
3. 09/04/133 VIT - SCSE
The following examples illustrate the initialization of data
members with different formats:
B(int a,int b):x(a),y(a+b)
B(int a,int b):x(a),y(x+b)
B(int a,int b):y(a),x(y+b)
4. 09/04/134 VIT - SCSE
Overloaded member functions
If the same member (data/function) exists in both the base
class and the derived class, the member in the derived class
will be executed.
Abstract class
Class with no object
Use for inheritance only
Can derive classes from an abstract class
5. 09/04/135 VIT - SCSE
class baseA
{
protected:
int x;
…..
….
};
class derivedB:public baseA
{
protected:
…..
….
};
class derivedD:public
baseA
{
protected:
…..
….
};
class abc:public
derivedB,public
derived
{
……
……
};
Virtual Base Class
Multipath inheritance
6. 09/04/136 VIT - SCSE
• The data member x is inherited twice in the derived class
abc, once through the derived class derivedB and again
through derivedD.
• This is wasteful.
• The above multiple repetition of the data member can be
corrected by changing the derived class derivedB and
derivedD into virtual base classes.
• Any base class which is declared using the keyword
virtual is called a virtual base class.
7. 09/04/137 VIT - SCSE
class baseA
{
protected:
int x;
…..
….
};
class derivedB:public virtual baseA
{
protected:
…..
….
};
class derivedD:public virtual
baseA
{
protected:
…..
….
};
class abc:public derivedB,public
derivedD
{
……
……
};
8. 09/04/138 VIT - SCSE
By making derivedB and derivedD into virtual base classes
for abc, a copy of the data member x is available only once.
9. 09/04/139 VIT - SCSE
class A
{
protected:
int x;
public:
void getdata();
void display();
};
class B:public virtual A
{
protected:
float y;
public:
void getdata();
void display();
};
class C:public virtual
A
{
protected:
char name[20];
public:
void getdata();
void display();
};
class D:public
B,public C
{
public:
void getdata();
void display();
};