How to use inheritance in Visual C++ (815670)
The information in this article applies to:
- Microsoft Visual C++ .NET (2003)
- Microsoft Visual C++ .NET (2002)
- Microsoft Visual C++ 2005 Express Edition
For a Microsoft Visual C# .NET version of this
article, see
307205. For a Microsoft Visual Basic .NET version of this
article, see
307222. SUMMARYInheritance is an important object-oriented concept. You can
use inheritance to build a hierarchy of related classes and to reuse the
functionality that is defined in existing classes. This step-by-step article
describes how to use inheritance in Microsoft Visual C++ .NET or in Microsoft Visual C++ 2005. In the
following examples, you define a base class that contains fields and methods
for a generic bank account. You then define a derived class that represents a
particular kind of bank account. The derived class inherits members from the
base class, overrides selected members, and then adds new members for the new
account. back to the topRequirementsThis article assumes that you are familiar with the following
topics:
- C++ syntax
- Managed Extensions for C++ and object-oriented concepts
back
to the topCreate a New Managed C++ Console Application- Start Visual Studio. NET or Visual Studio 2005, and then create a new Managed C++
Application project that is named
UseInheritance.
In Visual C++ .NET 2003, follow these steps:- Under Project Types, click Visual C++ Projects.
- Under Templates, click Console Application (.NET).
In Visual C++ 2005, follow these steps:
- Under Project Types, click Visual C++.
- Under Templates, click CLR Console Application.
- Save the project.
back
to the topCreate an Abstract Base Class and a Derived Class- In Solution Explorer, switch to the Class View. To do this,
click Class View on the View menu.
- Right-click the UseInheritance project, point to Add, and then click
Add Class.
Note In Visual C++ 2005, click Class, not Add Class. - In the Add Class dialog box, select
Generic C++ Class under Templates, and then
click Open.
Note In Visual C++ 2005, click C++ Class under Templates. - In the Generic C++ Class Wizard, type Account in the Class name box, and then click
Finish. The Account class appears as below:
#pragma once
class Account
{
public:
Account(void);
~Account(void);
};
To make the Account class an abstract managed C++ class, add the __abstract __gc keyword before the Account class:__abstract __gc class Account
{
public:
Account(void);
~Account(void);
};
Note You must add the common language runtime support compiler option (/clr:oldSyntax) in Visual C++ 2005 to successfully compile this code sample.
To do this, follow these steps:
- Click Project, and then click ProjectName Properties.
Note ProjectName represents the name of the project. - Expand Configuration Properties, and then click General.
- Click to select Common Language Runtime Support, Old Syntax (/clr:oldSyntax) in the Common Language Runtime support project setting on the right pane, click Apply, and then click OK.
For more information about the common language runtime support compiler options, visit the following Microsoft Web site: - Repeat steps 1-3 to add the SavingsAccount generic C++ class.
- In the Generic C++ Class Wizard, type SavingsAccount in the Class name box, and then click Finish. To make SavingsAccount a managed C++ class, add the __gc keyword before the SavingAccount class:
__gc class SavingsAccount :
public Account
{
public:
SavingsAccount(void);
~SavingsAccount(void);
}; back
to the topWrite Code for the Base Class- Open the Account.h file
- Use the mscorlib.dll as follows:
#using <mscorlib.dll> // You must use this code to take advantage of the .NET Framework. - Use the using directive on the System namespace so that you do not have to qualify declarations from
these namespaces later in your code. Add the following code in the Account.h
file:
using namespace System; // This shortcut avoids you having to type System::Console - In the Code View, add two fields to the Account class to represent the account balance and the name of the
account holder:
private:
String *name; // This is only accessible in base class.
protected:
double balance; // This is accessible in the base class and the derived class. - Override the Account constructor to initialize these fields:
public :
Account(String *szName, double bal)
{
this->name = szName;
this->balance = bal;
} - Add the following function to the class under the public
section. Because this method is not marked with the virtual keyword, it cannot be overridden in derived classes. The ChangeName function changes the name of the account holder:
void ChangeName(String *szNewName)
{
this->name = szNewName;
}
- Add the following functions to the class. The virtual keyword means that methods can be overridden in derived classes:
virtual void Credit(double amount)
{
this->balance += amount;
}
virtual void Debit(double amount)
{
this->balance -= amount;
}
virtual void Display()
{
Console::WriteLine(S"Name={0}, balance={1}",name,balance.ToString());
} - Add the following pure virtual function to the class under
the public section. This means that the function must be overridden in derived
classes:
virtual double CalculateBankCharge() = 0; Note Every member function
of an abstract __gc class must be defined unless the member function is a pure
virtual function. back to the topWrite Code for the Derived Class- Open the SavingsAccount.h file.
- Add a field to the SavingsAccount class:
private:
double minBalance; // If the balance drops below minBalance,
// the bank charges a fee on the account. - To initialize the fields in the base class and in this
class, override the SavingsAccount constructor under the public section:
SavingsAccount(String *nm, double bal, double min)
: Account(nm, bal) // Call the base class constructor first.
{
minBalance = min; // Then, initialize the fields in this class.
} - Add the following functions to the SavingsAccount class under the public section. These functions override the
functions that are inherited from the base class:
void Debit(double amount)
{
if (amount <= balance)
{
// Use balance. Balance is inherited from base class.
// Call Debit. Debit is inherited from base class.
SavingsAccount::Account::Debit(amount);
}
}
void Display()
{
SavingsAccount::Account::Display(); // Call Display. Display is inherited from base class.
Console::WriteLine(S"$5 charge if the balance goes below ${0}", minBalance.ToString());
} - You must override all pure virtual functions from the
abstract base class. Add the following method to the SavingsAccount class:
double CalculateBankCharge()
{
if (balance < minBalance)
return 5.00;
else
return 0.00;
} back
to the topVerify That It Works- Open the code for the UseInheritance.cpp file in the Code
View window. Add the following code to UseInheritance.cpp:
#include "SavingsAccount.h" - In the main function,
create a SavingsAccount object and then copy the following code:
SavingsAccount *sa = new SavingsAccount(S"Denise Smith", 100.00, 25);
sa->Display(); - Add the following code to call public methods in SavingsAccount or in Account:
sa->Credit(100);
sa->Debit(180);
sa->ChangeName(S"Samantha Smith");
sa->Display();
Console::WriteLine(S"Bank Charge: {0}",(sa->CalculateBankCharge()).ToString()); - Build the application.
- Set a breakpoint at the start of the Main function, and then start the application in the debugger mode.
Step into each statement, and then view the methods that are called while you are debugging
the application.
The application displays the following information on the console:
Name=Denise Smith, balance=100
$5 charge if balance goes below $25
Name=Samantha Smith, balance=20
$5 charge if balance goes below $25
Bank charge: $5 back
to the topREFERENCESFor more information about managed extensions for C++, visit
the following Microsoft Developer Network (MSDN) Web site: For more information about the rules for __gc types, visit the
following MSDN Web site: back to
the top
Modification Type: | Major | Last Reviewed: | 1/11/2006 |
---|
Keywords: | kbHOWTOmaster kbManaged kbLangCPP kbhowto kbInheritance KB815670 kbAudDeveloper kbAudITPRO |
---|
|
|
©2004 Microsoft Corporation. All rights reserved.
|
|