Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Constants in derived classes 1

Status
Not open for further replies.

timmay3141

Programmer
Dec 3, 2002
468
US
I am writing a program where I will have a base class with an int that should stay constant, and derived classes that will have their own unique values. For example, it would be something like this:

class BaseClass
{
public:
const int num;
BaseClass() : num(0) {};
};

class DerivedClass : public BaseClass
{
DerivedClass() : num(1) {};
}

Basically, I want all of the derived classes to have their own unique values for num. Unfortunately, this won't compile without making num a non-const integer, because you must initialize constants in the initialization list of the base class. Is there any way I could get around this but leave num as a const?
 
well, why you want to make that varible constant? As you said you are not able to change the value assigned to a constant, otherwise it wouldn't be constant anymore!...
 
I see what you are saying, but once I initialize it, it should never be changed. It really doesn't matter, as long as I just make sure I don't accidentally change it somewhere. I just wanted to make it a const so I couldn't accidentally change it.
 
Here's one way:

class BaseClass
{
protected:
BaseClass(int n) : num(n) {};
private:
const int num;
};

class DerivedClass : public BaseClass
{
public:
DerivedClass() : BaseClass(1) {};
}

Note the protected constructor ie can only be called from a derived class.



[sub]Nerdy signatures are as lame as the inconsistent stardates of STTNG.[/sub]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top