Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Function taking base class pointer but calling derived class function

I have two classes A (base) and B (deriving from A):

class A { };

class B : public A
{
    int data;
public:
    int get_data() { return data; }
};

Now I have a function test which takes base class pointer and calls derived class function :

void test(A * ptr)
{
    ptr->get_data();
}

But problem is ptr may point to A's object or B's object. If it points to B's object, then OK, but if to A's object, then it is a problem.

Moreover, I don't want to make get_data() virtual because data is not property of A's object.

How can I check if ptr points to B's object? One solution which I can think is dynamic_cast and check it for NULL. Is it the best solution or can I have a better solution ?

like image 868
Happy Mittal Avatar asked Aug 09 '26 02:08

Happy Mittal


1 Answers

This means your test function is lying. It is saying that it will accept a pointer to any A object, even types derived from A, but the function won't actually work for anything other than B. You're much better off taking a B*:

void test(B* ptr)
{
   ptr->get_data();
]
like image 71
Joseph Mansfield Avatar answered Aug 11 '26 18:08

Joseph Mansfield



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!