3

I'm coming from a C# background where I would write a class and constructor like this:

public class Grunt : GameObject
{
    public Grunt()
        : base()
    {
         // do stuff
    }
}

How do I write the constructors inheritance in C++? In both the header and the source. I know you don't have the 'base' keyword to work with, but otherwise is the syntax the same?

Dollarslice
  • 9,917
  • 22
  • 59
  • 87

4 Answers4

6
class Grunt : public GameObject
{
    Grunt()
        : GameObject()  // Since there are no parameters to the base, this line is actually optional.
    {
         // do stuff
    }
}

And strongly consider getting one of the fine C++ books at The Definitive C++ Book Guide and List

Community
  • 1
  • 1
Mark B
  • 95,107
  • 10
  • 109
  • 188
5

Yes, replace : base() with : GameObject().

But if there are no parameters the call is implied, as in C#

H H
  • 263,252
  • 30
  • 330
  • 514
3

You use the name of the base class in place of the 'base' keyword. This is necessary because of the possibility for multiple inheritance in C++. In the event of multiple base classes, you can call multiple base constructors by comma-delimiting the calls.

Dan Bryant
  • 27,329
  • 4
  • 56
  • 102
1

header:

template <int unique>
class base { 
public: 
    base();
    base(int param);
};

class derived: public base<1>, public base<2> {
public:
    derived();
    derived(int param);
};

source:

base::base() 
{}

base::base(int param) 
{}

derived::derived() 
: base<1>()
, base<2>() 
{}

derived::derived(int param) 
: base<1>(param)
, base<2>(param) 
{}

This clarifies how to inherit from multiple classes, inherit from template classes, construct base classes, shows how to pass parameters to base constructors, and shows why we have to use the name of the base.

Mooing Duck
  • 64,318
  • 19
  • 100
  • 158