I am a newcomer when its come to c++, when I study something about virtual functions and pure virtual functions, I found it's different than when I instantiate an object in different ways. This puzzles me a lot. I'll appreciate if you could help. The following are the codes and output.
#include <iostream>
using namespace std;
class A {
public:
int va;
int vb;
virtual void m1() {
cout << "this is A's m1() method" << endl;
}
void m3() {
cout << "this is A's m3() method" << endl;
}
};
class B : public A {
public:
void m1() {
cout << "this is B's m1() method" << endl;
}
void m2() {
cout << "this is B's m2() method" << endl;
}
void m3() {
cout << "this is B's m3() method" << endl;
}
};
int main() {
cout << "start" << endl;
A a1 = B();
a1.m1();
a1.m3();
cout << "===================" << endl;
A *a2;
a2 = new B();
a2->m1();
a2->m3();
delete[]a2;
/*
output:
this is A's m1() method
this is A's m3() method
===================
this is B's m1() method
this is A's m3() method
*/
return 0;
}
I'd like to know what's the difference between A a1 = B();
and A *a2; a2 = new B();
. Thank you for doing the help.