简体   繁体   中英

C++ call constructor in class A from class C (inherritence)

I'm stuck with a program I'm writing after a while of fidling around and completing "c++ through game programming" book.

The situation is as follows:

Class A
{
 public:
  A(int x)

 protected:
  int a;

};

A::A(int x):
 a(x)
{}

Class B : public A

Class C : public B
{
 public:
  C(int x)
};

C::C(int x)
{
  A(int x);
}

Am I able to call the constructor of class A in the constructor of class C?

From what I think I know: B is linked to A and C is linked to B so I should be able to get to the constructor of class A from C when I am able to reach member variables and functions by derriving it.

You can either try this:

class B : public A
{
public:
    B(int x) : A(x) { }
};

class C : public B
{
public:
    C(int x) : B(x) { }
};

Or if you're lazy (and using C++11 ):

class B : public A
{
public:
    using A::A(int);
};

class C : public B
{
public:
    using B::B(int);
};

This won't work:

class C : public B
{
public:
    C(int x) : A(x) { }
};

main.cpp: In constructor ‘C::C(int)’:

main.cpp:23:16: error: type ‘A’ is not a direct base of ‘C’

     C(int x) : A(x) { }

                ^

main.cpp:23:19: error: use of deleted function ‘B::B()’

     C(int x) : A(x) { }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM