Hello.
1.
I was wondering why is new Object() different from &Object()?
the keyword virtual says the function that is called, depends not on the type of pointer (or reference) but on the type of object.Code:#include <iostream> #include <vector> using namespace std ; class Base { public: int num ; Base() { cout << "Constructor for Base class" << endl; } void NotVirtual() { cout << "Base, Not Virtual" << endl ; } virtual void Virtual() { cout << "Base, Virtual" << endl ; } ~Base() { cout << "Destructor for Base class" << endl; } } ; class Derived: public Base { public: Derived():Base() { cout << "Constructor for Derived class" << endl; } void NotVirtual() { cout << "Derived, Not Virtual" << endl ; } void Virtual() { cout << "Derived, Virtual" << endl; } ~Derived() { cout << "Destructor for Derived class" << endl; } } ;
And in order for polymorphism to work..we need pointers..
If I was to run this code...Code:Base *b[3] ; b[0] = &Derived() ; b[1] = new Derived() ; b[2] = new Base() ;
the function call for b[1] and b[2] execute correctly..but b[0] doesn't, as in instead of printing "Derived constructor" It prints "Base constructor"..
In fact, the only difference between & and new i could see was that
&Derived() called the default destructor for base and derived class.
so if b[0] holds an invalid reference to &Derived(), since the object would have been destroyed..why do I not get a seg fault?
But since I didn't..why does it not print "Derived constructor" ? After the type of object is Derived()..
can you please clarify thanks. And your reply shouldn't make me lose my hair, although at this stage... :O



LinkBack URL
About LinkBacks



