constructor in inheritance. 2 constructors are used to initialized object. in inheritance the base...

5
Constructor in Inheritance

Upload: jeffery-stokes

Post on 17-Jan-2016

218 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Constructor in Inheritance. 2 Constructors are used to initialized object. In inheritance the base class contains default constructor then, the base class

Constructor in Inheritance

Page 2: Constructor in Inheritance. 2 Constructors are used to initialized object. In inheritance the base class contains default constructor then, the base class

2

Constructor in InheritanceConstructors are used to initialized object.In inheritance the base class contains default constructor then, the base class constructor is

automatically calledclass A{

protected: int a;public: A(){a=10;}

};class B:public A{

public:void show(){cout<<a;}

};void main(){

B obj;obj.show();

}

Page 3: Constructor in Inheritance. 2 Constructors are used to initialized object. In inheritance the base class contains default constructor then, the base class

3

Constructor in InheritanceIf base class contains parameterized constructor then the derived

class must have constructor ;Through the derived class constructor we can call base class

constructor.In main() we are creating object of only derived class, then

derived class constructor will call base class constructorThe derived class constructor function definition contains two part derived class constructor(arglist): initialization section{

constructor body;}colon separates the constructor declaration of the derived class

from the base class constructor.

Page 4: Constructor in Inheritance. 2 Constructors are used to initialized object. In inheritance the base class contains default constructor then, the base class

4

Constructor in Inheritanceclass A{

protected:int a;public: A(int x){a=x;}

};class B:public A{

int b;public:B(int x,int y):A(x){b=y;}void show(){cout<<a<<" "<<b;}

};

void main(){

B obj(1,2);obj.show();

}

Page 5: Constructor in Inheritance. 2 Constructors are used to initialized object. In inheritance the base class contains default constructor then, the base class

5

Constructor in InheritanceIn multiple inheritance

derived(int x,int y,int z):A(x),B(y){

c=z;}