Search code examples
c++compiler-errorsderived-classbase-class

Base Class constructor error


Possible Duplicate:
What is this weird colon-member syntax in the constructor?

I have the following base class and derived class;

class P {
 int n;
 public:
  P( int id );
  virtual  int getn();
  virtual  int toss( int x ) = 0; 
};

class RNP : public P {
  int n;
 public:
    RNP(  int id);
    int toss( int x );
};

I have created a constructor for RNP, but when i compile i get an error

player.cc:9:11: error: constructor for 'RNP' must explicitly initialize the base class 'P' which does not have a default constructor

How exactly do i initialize a base class within a derived class?


Solution

  • Simply by calling its constructor. It can be done in the initialization list, where you define RNP::RNP:

    RNP::RNP( int id )
    :
        P( id )
    {
        //...
    }