In C++, I have several classes inheriting from an abstract super class. Subclasses have a static attribute sharing the same name type
but of course have different values. My question is what is the best approach to implement this and what are the pros and cons for each implementation.
PS: There are some related discussions like here but most don't explain why approach (which works on my machine) 1 below should not be used. Besides, the subclass methods in approach 2 are not static and wwe will have to get an instance to invoke them.
Apporach 1: uinitialized const static
in superclass
class Abstract {
public:
const static int type;
};
class C1: public Abstract {
public:
const static int type = 1;
};
class C2 : public Abstract {
public:
const static int type = 2;
};
Approach 2: using virtual functions instead of variables
class Abstract {
public:
virtual int get_type() = 0;
};
class C1: public Abstract {
public:
int get_type() {return 1;}
};
class C2 : public Abstract {
public:
int get_type() {return 2;}
};
Other approaches that I'm not aware of...
EDIT:
As some answers/comments mentioned below, I'm trying to identify actual type at runtime. However I cannot really think of a nicer design.
To make it concrete, let's say Abstract=EduInst
for educational institution, C1=Univ
, C2=College
, etc. I have a std::map<Key, EduInst*>
storing all institutions, which are generated at runtime depending on user input. At times I need to operate only on Univ
s or College
s. What is a good way to implement this?