Sep 26, 2010 at 5:25am UTC
I have a question about the following virtual.cpp code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
#include <iostream>
using namespace std;
class Base {
public :
Base() {}
virtual void A() { cout << "Base A" << endl; }
void B() { cout << "Base B" << endl; }
};
class One : public Base {
public :
One() {}
void A() { cout << "One A" << endl; }
void B() { cout << "One B" << endl; }
};
class Two : public Base {
public :
Two() {}
void A() { cout << "Two A" << endl; }
void B() { cout << "Two B" << endl; }
};
int main()
{
Base* a[3];
a[0] = new Base;
a[1] = new One;
a[2] = new Two;
for ( unsigned int i=0; i < 3; i++)
{
a[i]->A();
a[i]->B();
}
return 0;
}
Why does B() behave differently than A()? Is it that A() is a constructor of class Virtual while B() is simply a method?
Last edited on Sep 26, 2010 at 5:25am UTC
Sep 26, 2010 at 5:27am UTC
1 2 3 4 5 6
Base A
Base B
One A
Base B
Two A
Base B
When i make B() a constructor it will run to produce:
1 2 3 4 5 6
Base A
Base B
One A
One B
Two A
Two B
which is what i want it to do.
Last edited on Sep 26, 2010 at 5:45am UTC
Sep 26, 2010 at 6:07am UTC
Can someone simply check to see if i im right. Im pretty sure its because A() is a constructor and B() is not
Sep 26, 2010 at 6:21am UTC
and just for reference, what do we call B()?
Sep 26, 2010 at 6:22am UTC
constructor? A constructor must have the same name that the class.
Both are methods, but the virtual keyword tell the compiler that you want to use polymorphism.
So in runtime determines to which type of object is your pointer pointing.
If you don't put virtual, always call to the type of the pointer.
EDIT: it's just say the same as m4ster r0shi
Last edited on Sep 26, 2010 at 6:32am UTC
Sep 26, 2010 at 6:24am UTC
Ok then got it :D thank you guys so much!
Sep 26, 2010 at 6:53am UTC
where are your delete[] or a handle class to handle your memory?
Last edited on Sep 26, 2010 at 7:27am UTC
Sep 26, 2010 at 7:13am UTC
They couldn't come. They are in a very important meeting.