Reputation: 1694
I'm wondering how can I make unmodifiable a parent class member which will be different for each derived class.
My code now assigns its value correctly (depending on the Child class that calls the parent class' constructor), but m_type
can be easily modified (in myfunction
, for example) and that's what I'd like to avoid.
#include <iostream>
enum Piece_type{ king=1, queen=3, rook=3, bishop=4, knight=5, pawn=6};
class Piece
{
protected:
Piece_type m_type; // static Piece_type m_type; <- doesn't work
Piece(Piece_type ex): m_type(ex) {}
};
class Pawn: public Piece
{
public:
Pawn():Piece(pawn) {} // To initialise m_type as pawn for all my Pawn objects
void myfunction()
{
std::cout<<"My piece type is "<< m_type<<std::endl;;
m_type= knight; // This is the assignation I want to avoid happening
std::cout<<"My new piece type i "<<m_type<<std::endl;
}
};
My question is related to this one, but inheritance doesn't seem to make possible to declare a static variable and define its value through a member initializer.
I've found how to call the parent/base class constructor from the Child class in this question.
Thanks in advance,
Eduardo
Edit
I've slightly modified it so that not to confuse anyone, because const
does work where I said it didn't.
Upvotes: 0
Views: 78
Reputation: 29072
They only ways to prevent a derived type from modifying it's parent's members is to make those members private
or const
. Since you can't make the member const
the only other way would be to declare the member private
and adding a protected
accessor method such as :
Piece_type get_type() const
{
return m_type;
}
This way, derived classes can call get_type()
to know m_type
's value but can't access it directly, preventing them from writing to it.
Upvotes: 3
Reputation: 63154
Well, you didn't fall into the usual mistake of trying to use const
member variables without a member initializer list, so const
is all you need really:
class Piece
{
protected:
Piece_type const m_type;
Piece(Piece_type ex) : m_type(ex) { }
};
class Pawn : public Piece
{
public:
Pawn() : Piece(pawn) { }
void myfunction()
{
// m_type = knight; // Compile-time error
}
};
Upvotes: 3