GeekInterview.com
Series: Subject: Topic:
Question: 12 of 267

Abstract class - can we create pointer to abstract class?

Asked by: ak.nextptr | Member Since Jan-2012 | Asked on: Mar 21st, 2012

View all questions by ak.nextptr   View all answers by ak.nextptr

Showing Answers 1 - 1 of 1 Answers
supreet singh

Answered On : Mar 25th, 2012

yes we can create a pointer to an abstract class, which could be actually pointing to the objects of its derived classes. In this way, a container of base class pointers can be created which can also store derived class objects. Thus dynamic binding will take place for the virtual methods and class specific methods will be called. eg.

Code
  1.  
  2. class Base
  3. {
  4. public:
  5.   virtual void method1();
  6. }
  7.  
  8. class Derived:public Base
  9. {
  10.   void method1()
  11.    {
  12.      cout<<"in derived 1"<<endl;
  13.    }
  14. }
  15.  
  16. class Derived2:public Base
  17. {
  18.   void method1()
  19. {
  20.   cout<<"in derived 2"<<endl;
  21.  
  22. }
  23. }
  24. vector<Base *> v;
  25. v.add(new Derived1());
  26. v.add(new Derived2());
  27.  
  28. v[0]->method1();
  29. v[1]->method1();

____________ output will be: in derived 1 in derived 2

  
Login to rate this answer.

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

Related Open Questions

Ads

Connect

twitter fb Linkedin GPlus RSS

Ads

Interview Question

 Ask Interview Question?

 

Latest Questions

Interview & Career Tips

Get invaluable Interview and Career Tips delivered directly to your inbox. Get your news alert set up today, Once you confirm your Email subscription, you will be able to download Job Inteview Questions Ebook . Please contact me if you there is any issue with the download.