Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass Parameter to Base Class Constructor while creating Derived class Object

Consider two classes A and B

class A { public:     A(int);     ~A(); };  class B : public A { public:     B(int);     ~B(); };   int main() {     A* aobj;     B* bobj = new bobj(5);     } 

Now the class B inherits A.

I want to create an object of B. I am aware that creating a derived class object, will also invoke the base class constructor , but that is the default constructor without any parameters.

What i want is that B to take a parameter (say 5), and pass it on to the constructor of A. Please show some code to demonstrate this concept.

like image 561
CodeCrusader Avatar asked May 16 '13 11:05

CodeCrusader


People also ask

Can we pass parameters to base class constructor though derived class or?

Explanation: Yes, we pass parameters to base class constructor though derived class or derived class constructor.

What parameters are required to pass to a class constructor?

This method has four parameters: the loan amount, the interest rate, the future value and the number of periods. The first three are double-precision floating point numbers, and the fourth is an integer.

Can you assign a derived class object to a base class object?

Object Slicing in C++ In C++, a derived class object can be assigned to a base class object, but the other way is not possible.

Can a derived class have a constructor with default parameters?

A derived class cannot have a constructor with default parameters.


2 Answers

Use base member initialisation:

class B : public A { public:     B(int a) : A(a)     {     }     ~B(); }; 
like image 133
Bathsheba Avatar answered Sep 29 '22 08:09

Bathsheba


B::B(int x):A(x) {     //Body of B constructor } 
like image 23
SomeWittyUsername Avatar answered Sep 29 '22 09:09

SomeWittyUsername