Pass Parameter to Base Class Constructor while cre

2019-03-10 22:33发布

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.

4条回答
劳资没心,怎么记你
2楼-- · 2019-03-10 23:14

Use base member initialisation:

class B : public A
{
public:
    B(int a) : A(a)
    {
    }
    ~B();
};
查看更多
成全新的幸福
3楼-- · 2019-03-10 23:15

If you are using your derived class constructor just to pass arguments to base class then you can also do it in a shorter way in C++11:

class B : public A
{
    using A::A;
};

Note that I have not even used "public" access specifier before it. This is not required since inherited constructors are implicitly declared with same access level as in the base class.

For more details, please refer to section Inheriting constructors at: https://en.cppreference.com/w/cpp/language/using_declaration

Also you may refer to https://softwareengineering.stackexchange.com/a/307648 to understand limitations on constructor inheritance.

查看更多
你好瞎i
4楼-- · 2019-03-10 23:18
B::B(int x):A(x)
{
    //Body of B constructor
}
查看更多
虎瘦雄心在
5楼-- · 2019-03-10 23:20

class A { public: int aval;

A(int a):aval(a){};
~A();

};

class B : public A { public: int bval;

B(int a,int b):bval(a),A(b){};
~B();

};

int main() {

  B *bobj = new bobj(5,6);
//or 
  A *aobj=new bobj(5,6); 

}

In this case you are assigning the values for base class and derived class .

查看更多
登录 后发表回答