interface - question on basic oops concepts -


i want find answer question

let a parent class b,c child classes.

now create objects follows,

  1. a o1 = new a();
  2. b o2 = new b();
  3. c o3 = new c();

  4. a o4 = new b();

  5. b o5 = new a();
  6. c o6 = new b();

from these create errors , why.. got confused lot because 6 know error because b may have specialized variables , 7 possible , 8 not possible.

if i'm wrong please correct me , also,

  1. a o7 = o4;
  2. b 08 = o5;

kindly suggest me right answers , explanations , give me links tutorials kind of puzzles.

assuming objects of pointer types-

1. *o1 = new a();   // correct 2. b *o2 = new b();   // correct 3. c *o3 = new c();   // correct  4. *o4 = new b(); // pointer derived class type-compatible pointer base class. casting acts default. 5. b *o5 = new a(); // wrong because other-wise relationship of above comment isn't true. though there separate concept called down-casting isn't valid here. 6. c *o6 = new b();  // wrong : c, b has no hierarchial relationships  7. *o7 = o4;      // correct because o4, o7 both of same type 8. b *o8 = o5;      // wrong. since, 5 wrong. 

explanation 4 & 5:

  1. new b() calls a's constructor followed b's constructor. so, have sub-objects of type a*,b*. since, there sub-object of type a*, lvalue can point equal of type a*. helpful access base class overridden virtual methods in derived class.

  2. new a() constructs object of type a* , returns it's address. so, return type of a* receiving type of b*. so, both incompatible , wrong.

example: output results

#include <iostream> using namespace std; class {     public:     a(){         cout << " \n constructor \n";     }     virtual ~a(){         cout << "\n destructor \n";     } };  class b: public {     public:     b(){         cout << " \n constructor b \n";     }     ~b(){         cout << "\n destructor b \n";     } 

};

class c: public {     public:     c(){         cout << " \n constructor c \n";     }     ~c(){         cout << "\n destructor c \n";     } 

};

int main() {     a* obj1 = new a;     std::cout<< "******************************" << std::endl;      a* obj2 = new b;     std::cout<< "******************************" << std::endl;      a* obj3 = new c;     std::cout<< "******************************" << std::endl;      delete obj1;     std::cout<< "******************************" << std::endl;      delete obj2;     std::cout<< "******************************" << std::endl;      delete obj3;     std::cout<< "******************************" << std::endl;      return 0; } 

results:

constructor


constructor

constructor b


constructor

constructor c


destructor


destructor b

destructor


destructor c

destructor


notice order of destruction reverse order of construction.


Comments

Popular posts from this blog

apache - Add omitted ? to URLs -

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

php - How can I stop spam on my custom forum/blog? -