Reputation: 15
This is follow up question to this. Now I have this code:
class A
{
protected:
string name;
public:
A(string a) {name = a;}
virtual string getName() {return "A name: " + name;}
};
class B: public A
{
public:
using A::A;
string getName() {return "B name: " + name;}
string newMethod() {return "B name new: " + name;}
};
void print_name(A & obj)
{
// HOW to check if obj is B, and call newMethod then.
cout << obj.newMethod() << endl; // THIS LINE HAS ERROR below
}
int main()
{
A a("a");
B b("b");
print_name(a);
print_name(b);
return 0;
}
I get error 'class A' has no member named 'newMethod'. I know its becasue newMethod is only in B.
But how can I check if obj in print_name is A or B, and call newMethod only if obj is B?
Upvotes: 0
Views: 89
Reputation: 141618
Well, this is not a great design. But you can write:
cout << dynamic_cast<B &>(obj).newMethod() << endl;
This will throw an exception if obj
is not actually a B
. If you don't want an exception then you can cast to a pointer:
B *ptr = dynamic_cast<B *>(&obj);
if ( ptr )
cout << ptr->newMethod() << endl;
Upvotes: 2
Reputation: 99124
This is the way to use a virtual method:
class B: public A
{
public:
...
// new implementation of virtual method, old signature
string getName() {return "B name new: " + name;}
};
void print_name(A & obj)
{
cout << obj.getName() << endl;
}
Upvotes: 2
Reputation: 238299
You could use dynamic casting:
void print_name(A & obj)
{
B * b = dynamic_cast<B*>(&obj);
if (b != nullptr) {
cout << b->newMethod() << endl;
} else {
cout << obj.getName() << endl;
}
}
Upvotes: 0
Reputation: 1473
Here is trick, use dynamic_cast
TYPE& dynamic_cast<TYPE&> (object);
TYPE* dynamic_cast<TYPE*> (object);
dynamic_cast can only be used with pointers and references to classes (or with void*). Its purpose is to ensure that the result of the type conversion points to a valid complete object of the destination pointer type.
Upvotes: 2
Reputation: 1032
it is failing since the newMethod is not declared in class A,obviously the object reference of the class A will not find the method named newMethod. To achieve what you want you should use concepts of RTTI use typeof operator.
Upvotes: 0