coding

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
What is your output?
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
Can someone simply check to see if i im right. Im pretty sure its because A() is a constructor and B() is not
A() is not a constructor. A() is a virtual member function. Base(), One() and Two() are constructors.
And yes, the reason A() behaves differently is that it is virtual.

More info on virtual functions -> http://cplusplus.com/doc/tutorial/polymorphism/
and just for reference, what do we call B()?
A member function.
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
Ok then got it :D thank you guys so much!
where are your delete[] or a handle class to handle your memory?
Last edited on
They couldn't come. They are in a very important meeting.
Topic archived. No new replies allowed.