Initializing inherited protected Members of superclass

D

durgadeep

I have the following program. It has two classes Species and its sub
class NajaNaja. Now I am trying to do this,

The following gives me an error.

NajaNaja::NajaNaja(int age, int weight, KINDOF KINDOF): Species(age),
TypeOf(KINDOF), Heavy(weight)
{
std::cout << "NajaNaja(int, int, KINDOF) constructor...\n";
}

The following works if I do

NajaNaja::NajaNaja(int age, int weight, KINDOF KINDOF): Species(age),
TypeOf(KINDOF)
{
Heavy = weight;
std::cout << "NajaNaja(int, int, KINDOF) constructor...\n";
}


Why is there such a restriction ?


## PROGRAM BEGIN ###

#include <iostream>

enum KINDOF { COBRA, PYTHON, RATTLESNAKE };

class Species
{
public:
// constructors
Species();
Species(int age);
~Species();

//accessors
int HowOld() const { return Age; }
void SetOld(int age) { Age = age; }
int GetWeight() const { return Heavy; }
void SetWeight(int weight) { Heavy = weight; }

//Other methods
void Hiss() const { std::cout << "Species sound!\n"; }
void Snore() const { std::cout << "shhh. I'm Snoreing.\n"; }

protected:
int Age;
int Heavy;
};

class NajaNaja : public Species
{
public:
// Constructors
NajaNaja();
NajaNaja(int age);
NajaNaja(int age, int weight);
NajaNaja(int age, KINDOF kindof);
NajaNaja(int age, int weight, KINDOF kindof);
~NajaNaja();

// Accessors
KINDOF GetKINDOF() const { return TypeOf; }
void SetKINDOF(KINDOF kindof) { TypeOf = kindof; }

// Other methods
void WagTail() { std::cout << "Tail wagging...\n"; }
void BegForFood() { std::cout << "Begging for food...\n"; }

private:
KINDOF TypeOf;
};
 
A

Alf P. Steinbach

* (e-mail address removed):
I have the following program. It has two classes Species and its sub
class NajaNaja. Now I am trying to do this,

The following gives me an error.

NajaNaja::NajaNaja(int age, int weight, KINDOF KINDOF): Species(age),
TypeOf(KINDOF), Heavy(weight)
{
std::cout << "NajaNaja(int, int, KINDOF) constructor...\n";
}

You can't initialize a member of a base class in the initializer list.

But you can initialize the base class (calling its constructor).


Cheers, & hth.,

- Alf
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,901
Latest member
Noble71S45

Latest Threads

Top