Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ checking the type of reference

Tags:

c++

Is it bad design to check if an object is of a particular type by having some sort of ID data member in it?

class A
{

private:
  bool isStub;
public:
 A(bool isStubVal):isStub(isStubVal){}
 bool isStub(){return isStub;}


};

class A1:public A
{
 public:
 A1():A(false){}
};

class AStub:public A
{
 public:
 AStub():A(true){}
};

EDIT 1: Problem is A holds a lot of virtual functions, which A1 doesn't override but the stub needs to, for indidicating that you are working on a stub instead of an actual object. Here maintainability is the question, for every function that i add to A, i need to override it in stub. forgetting it means dangerous behaviour as A's virtual function gets executed with stub's data. Sure I can add an abstract class ABase and let A and Astub inherit from them. But the design has become rigid enough to allow this refactor. A reference holder to A is held in another class B. B is initialized with the stub reference, but later depending on some conditions, the reference holder in B is reinitialized with the A1,A2 etc.. So when i do this BObj.GetA(), i can check in GetA() if the refholder is holding a stub and then give an error in that case. Not doing that check means, i would have to override all functions of A in AStub with the appropriate error conditions.

like image 314
excray Avatar asked Dec 02 '22 06:12

excray


2 Answers

Generally, yes. You're half OO, half procedural.

What are you going to do once you determine the object type? You probably should put that behavior in the object itself (perhaps in a virtual function), and have different derived classes implement that behavior differently. Then you have no reason to check the object type at all.

In your specific example you have a "stub" class. Instead of doing...

if(!stub) 
{ 
    dosomething; 
} 

Just call

object->DoSomething();

and have the implemention in AStub be a empty

like image 153
Terry Mahaffey Avatar answered Dec 23 '22 00:12

Terry Mahaffey


Generally yes. Usually you want not to query the object, but to expect it to BEHAVE the proper way. What you suggest is basically a primitive RTTI, and this is generally frowned upon, unless there are better options.

The OO way would be to Stub the functionality, not check for it. However, in the case of a lot of functions to "stub" this may not seem optimal.

Hence, this depends on what you want the class to really do.

Also note, that in this case you don't waste space:

class A
{
  public:
    virtual bool isStub() = 0;
};

class A1:public A
{
  public:
    virtual bool isStub() { return false; };
};

class AStub:public A
{
  public:
    virtual bool isStub() { return true; };
};

... buuut you have a virtual function -- what usually is not a problem, unless it's a performance bottleneck.

like image 43
Kornel Kisielewicz Avatar answered Dec 22 '22 23:12

Kornel Kisielewicz