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?

有帮助吗?

解决方案

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

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

其他提示

Usually you need to do it in the derived class constructor by using "::" operator

Using : after the derived class' constructor arguments

RNP::RNP(  int id): P (id)
{
//do your stuff
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top