This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Finding the type of an object in C++
I have a question with checking pointers to see if they conform to a particular derived class and take necessary action.
Lets say I currently have 2 derived classes DerivedClass1 and DerivedClass2 and the base class BaseClass. I would like to check the following action.
Ptr<BaseClass> ptr;
if (ptr points to DerivedClass1)
{
action1
}
else
{
action2
}
How do I check for ptr points to a particular DerivedClass?
If you were to think a bit more object-orientedly, you would just make it a virtual method on the base class:
Ptr<BaseClass> ptr;
ptr->Action();
and have each class implement it as needed. I realize this isn't an actual answer, but it's an alternative way of accomplishing your goal which is often considered to be better, which is why I think it's worth mentioning.
If BaseClass is polymorphic (contains virtual functions), you can test:
if (dynamic_cast<DerivedClass1*>(ptr.get()))
But usually you should use dynamic dispatch as unwind suggests, possibly a Visitor pattern, for this sort of thing. Littering your code with dynamic_cast makes it hard to maintain. I use dynamic_cast almost NEVER.
if(dynamic_cast<DerivedClass1*>(ptr))
{
// Points to DerivedClass1
}
else if(dynamic_cast<DerivedClass2*>(ptr)
{
// Points to DerivedClass2
}
Related
This question already has answers here:
Polymorphism in C++
(7 answers)
Closed 2 years ago.
int main() {
doSomething(something);
}
string doSomething(Thing *x);
Here, doSomething is a function and Thing is a class. Now, I also have another inherited class called subThing, and I also want to doSomething to a pointer of subThing.
What do you call the concept of using pointers to inherited classes? I am asking this so that I can research more on this topic.
Look up “Polymorphism”.
When subThing is derived from Thing, an instance of subThing is also an instance of Thing, so a subThing* pointer can be used anywhere a Thing* pointer can be used. Same thing with subThing& and Thing& references. Just watch out for “Object Slicing”. Polymorphic access to an object only works when accessing the object via a pointer or reference.
This question already has answers here:
C++ cast to derived class
(4 answers)
Closed 7 years ago.
Let's imagine a situation where I have an abstract class named 'Base' with a virtual pure method named foo(), and 2 children (Inherited1 and Inherited2) that both implement this method in their own way. Now let's say that one of these children (Inherited1) needs another method called bar() that would make no sense to implement in Inherited2.
In my main, i Have
Base * randomObject = new Inherited1();
I can't access this method using
random->bar();
What should I do. Like I said, it would make no sense to implement it in inherited2, so I can't simply put another virtual method in Base, or should I?
If you had a variable
Base* randomObject = new Inherited1();
You could cast it down to the base class
Inherited1* foo = static_cast<Inherited1*>(randomObject);
foo->bar();
But you have to be sure that the pointer is indeed of that derived class otherwise static_cast isn't safe. There are a number of ways to do this, such as storing an enum in the derived classes that you can check via a virtual getter, or checking if the result of a dynamic_cast is nullptr, but that is slower.
This question already has answers here:
Prefer composition over inheritance?
(35 answers)
Closed 8 years ago.
I'm quite new in C++ and I would like to learn good practices from the beginning, so my question explained with an example is:
Having:
class A
{
int mNumber;
};
If I need to use class A inside class B, what is better?to include an object?
class B
{
A * mpA;
int mColor;
};
Or inherit from Class A?
class B : public A
{
int mColor;
};
Is there any good habit talking in a generally way to do this?
Prefer composition over inheritance - however remember that for each particular situation, the other approach might be better.
Composition is:
class A
{
B b;
};
Inheritence is:
class A : public B
{
};
Use the first when the relationship is "has-a" and the latter when it is "is-a".
Your example is a loose type of composition - if the member is a pointer, it doesn't (necessarily) signify ownership.
This question already has answers here:
When should I make explicit use of the `this` pointer?
(12 answers)
Closed 9 years ago.
I wonder if there is some reason or not to use this in a attribute class?
class Foo
{
private:
int m_foo;
public:
int getIntance() { return this->m_foo; }
}
Other than the fact its say that this is the current class, are there others reasons?
No, do not use it. In that particular case, it is not needed, and this is less typing :
int getIntance() { return m_foo; }
Less you write is better. Even for people reading you code (they'll have less to read)
this is less typing. It is not mandatory in this particular case. There is no reason to use this keyword unless if you want to pass the current instance of your object to a function for example.
You can simply write :
int getIntance() { return m_foo; }
It is weird to call a method getInstance to return an int. It is quite uncommon...
There's no reason to use this, except when, for example, you want something outside the class to point to your instance (let's say, you add your instance - this - to a list of pointers).
In your example, this is redundant, since m_foo could easily have been returned by return m_foo; without any problem.
However, this can only be used in non-static member functions, or else it won't compile.
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
How to force child same virtual function call its parent virtual function first
I have a class hierarchy where each derived class overrides a given virtual function and starts its implementation by calling the one in its parent class. The goal is to have each of the derived implementation to be executed, but I do not like the way I do it.
For example, I have this class:
class base
{
public:
void do_stuff() { do_something(); }
virtual void do_something() { }
};
Then I derive this class on several levels:
class derived_10:
public derived_9 // which inherit from derived_8 and so on until derived_0
// which inherit from base
{
public:
virtual void do_something()
{
// this will also call derived_8::do_something() and so on
// until base::do_something()
derived_9::do_something();
// then, some stuff
}
};
I'm looking for a solution that will make sure that all derived_x::do_something() will be called in sequence when base::do_stuff() is called, without having to expect the derived classes to do this themselves. Do you have an idea of the best way to get this behavior ?
I've already asked a very similar question before: Calling overriden class methods as a chain in C++
The answer I've accepted pointed at your own solution. I can give you an idea about an alternative though. Constructors and destructors already have this behavior in C++, you might want to consider restructuring your code, so that the work is done during the construction or the destruction of an object that belongs to a class in a hierarchy. I'm not sure you'll be able to make this worth the effort though. On the other hand, you never know what you can get out of some template metaprogramming + some preprocessor magic.