سؤال

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