0

Say I have

Class Base {}

Class Child: public Base {
   void alert() { printf("alert"); }
}

How do I call alert() with type Base?

Base *p = new Child();
p->alert() // error, Base does not have alert method

I've tried this but doesn't work as well.

p->Child::alert() // error, Base does not have alert method

I can fix the problem if I move alert() to Base of course but I don't want Base to have alert() so it won't pass on to other children.

2
  • 1
    C has no classes. And C/C++ isn't a thing. Commented Dec 25, 2014 at 16:22
  • C++ is case sensitive, change Class -> class and Public -> public. Commented Dec 25, 2014 at 16:26

2 Answers 2

3

"How do I call alert() with type Base?"

To do so make Base an abstract class

class Base {
   virtual void alert() = 0; // <<<<<
}

class Child: public Base {
   void alert() { printf("alert"); }
}

If you really want or need to avoid providing alert() in your base class you can use a static_cast<Child*>

static_cast<Child*>(p)->alert();
Sign up to request clarification or add additional context in comments.

2 Comments

Yeah, I can add a virtual method in Base. Is this the only way? I don't want other children try to define alert()
@Mistergreen You can still provide an (empty) implementation in Base to avoid this. Casting correctly is another option (see my update).
0

When you have a child class object which is having a base class reference type you cannot call the methods which are only present in child class you can only call the methods which are common to both classes.The base class function is over-ridden in this case unless we use super.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.