Constructors cannot be virtual functions because constructors must be determined when the constructor is invoked to create the object, so constructors cannot be virtual functions.
The destructor can be a virtual function.
1. Parent Class Father.h:
Copy Code code as follows:
#pragma once
Class Father
{
Public
Father (void);
Virtual ~father (void);
virtual int getcount ();
Public
int count;
};
Father.cpp
Copy Code code as follows:
#include "StdAfx.h"
#include "Father.h"
#include <iostream>
using namespace Std;
Father::father (void)
{
Count = 1;
cout<< "Father is called. Count = "<<count<<endl;
}
Father::~father (void)
{
cout<< "~father is called." <<endl;
}
int Father::getcount ()
{
cout<< "Father::getcount () Count =" <<count<<endl;
return count;
}
2. Sub-class Child.h:
Copy Code code as follows:
#pragma once
#include "Father.h"
Class Child:
Public Father
{
Public
Child (void);
Virtual ~child (void);
virtual int getcount ();
int Getage ();
Public
int age;
};
Child.cpp
Copy Code code as follows:
#include "StdAfx.h"
#include "Child.h"
#include <iostream>
using namespace Std;
Child::child (void)
{
Count = 2;
Age = 20;
cout<< "Child is called. Count = "<<count<<", age = "<<age<<endl;
}
Child::~child (void)
{
cout<< "~child is called." <<endl;
}
int Child::getcount ()
{
cout<< "Child::getcount () Count =" <<count<<endl;
return count;
}
int Child::getage ()
{
cout<< "child::getage () Age =" <<age<<endl;
return age;
}
3. Test class Test.cpp
Copy Code code as follows:
#include "stdafx.h"
#include <cstdlib>
#include <iostream>
#include "Child.h"
using namespace Std;
int _tmain (int argc, _tchar* argv[])
{
Father *father1 = new Father ();
cout<< "father1 count =" <<father1->getcount () <<endl;
Delete Father1;
cout<< "************** father1 end *****************" <<endl<<endl;
Father *father2 = new Child ();
cout<< "father2 count =" <<father2->getcount () <<endl; Father2 don ' t have Getage () method
Delete Father2;
cout<< "************** father2 end *****************" <<endl<<endl;
Child *child = new Child ();
cout<< "Child count =" <<child->getcount () <<endl;
cout<< "Child age =" <<child->getage () <<endl;
Delete child;
cout<< "************** child End *****************" <<endl<<endl;
GetChar ();
return 0;
}
4. Output Result:
Father is called. Count = 1
Father::getcount () Count = 1
Father1 count = 1
~father is called.
Father1 End *****************
Father is called. Count = 1
Child is called. Count = 2, age = 20
Child::getcount () Count = 2
Father2 count = 2
~child is called.
~father is called.
Father2 End *****************
Father is called. Count = 1
Child is called. Count = 2, age = 20
Child::getcount () Count = 2
Child count = 2
Child::getage () Age = 20
Child age = 20
~child is called.
~father is called.
Child End *****************