interface - question on basic oops concepts -
i want find answer question
let a parent class b,c child classes.
now create objects follows,
- a o1 = new a();
- b o2 = new b();
c o3 = new c();
a o4 = new b();
- b o5 = new a();
- 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,
- a o7 = o4;
- 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:
new b()
callsa's
constructor followedb's
constructor. so, have sub-objects of typea*
,b*
. since, there sub-object of typea*
, lvalue can point equal of typea*
. helpful access base class overridden virtual methods in derived class.new a()
constructs object of typea*
, returns it's address. so, return type ofa*
receiving type ofb*
. 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
Post a Comment