0

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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
John Smith
  • 27
  • 1
  • 9

3 Answers3

1

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

RNP::RNP( int id )
:
    P( id )
{
    //...
}
Kiril Kirov
  • 37,467
  • 22
  • 115
  • 187
0

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

ISTB
  • 1,799
  • 3
  • 22
  • 31
0

Using : after the derived class' constructor arguments

RNP::RNP(  int id): P (id)
{
//do your stuff
}
il_guru
  • 8,383
  • 2
  • 42
  • 51