Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
533 views
in Technique[技术] by (71.8m points)

c++ - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use base member initialisation:

class B : public A
{
public:
    B(int a) : A(a)
    {
    }
    ~B();
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...