Microsoft KB Archive/815670

= How to use inheritance in Visual C++ =

Article ID: 815670

Article Last Modified on 11/14/2007

-

APPLIES TO


 * Microsoft Visual C++ .NET 2003 Standard Edition
 * Microsoft Visual C++ .NET 2002 Standard Edition
 * 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.



 IN THIS TASK
 * Summary
 * Requirements
 * Create a New Managed C++ Console Application
 * Create an Abstract Base Class and a Derived Class
 * Write Code for the Base Class
 * Write Code for the Derived Class
 * Verify That It Works
 * REFERENCES



SUMMARY
Inheritance 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 top

Requirements
This article assumes that you are familiar with the following topics:
 * C++ syntax
 * Managed Extensions for C++ and object-oriented concepts

back to the top

Create 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.</li></ol> </li> Save the project.</li></ol>

back to the top

Create 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.</li> Right-click the UseInheritance project, point to Add, and then click Add Class.

Note In Visual C++ 2005, click Class, not Add Class.</li> 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.</li>  In the Generic C++ Class Wizard, type Account in the Class name box, and then click Finish. The Account class appears as below:
 * 1) 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.</li> Expand Configuration Properties, and then click General.</li> 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.</li></ol>

For more information about the common language runtime support compiler options, visit the following Microsoft Web site:

/clr (Common Language Runtime Compilation)

http://msdn2.microsoft.com/en-us/library/k8d11d4s.aspx

</li> Repeat steps 1-3 to add the SavingsAccount generic C++ class.</li>  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); }; </li></ol>

back to the top

Write Code for the Base Class
 Open the Account.h file</li>  Use the mscorlib.dll as follows: <li> 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 </li> <li> 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. </li> <li> Override the Account constructor to initialize these fields: public : Account(String *szName, double bal) {       this->name = szName; this->balance = bal; } </li> <li> 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; } </li> <li> 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; }
 * 1) using <mscorlib.dll> // You must use this code to take advantage of the .NET Framework. </li>

virtual void Display {       Console::WriteLine(S&quot;Name={0}, balance={1}&quot;,name,balance.ToString); } </li> <li> 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; </li></ol>

Note Every member function of an abstract __gc class must be defined unless the member function is a pure virtual function.

back to the top

Write Code for the Derived Class
<ol> <li>Open the SavingsAccount.h file.</li> <li> Add a field to the SavingsAccount class: private: double minBalance; // If the balance drops below minBalance, // the bank charges a fee on the account. </li> <li> 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. } </li> <li> 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&quot;$5 charge if the balance goes below ${0}&quot;, minBalance.ToString); } </li> <li> 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; } </li></ol>

back to the top

Verify That It Works
<ol> <li> Open the code for the UseInheritance.cpp file in the Code View window. Add the following code to UseInheritance.cpp: <li> In the main function, create a SavingsAccount object and then copy the following code: SavingsAccount *sa = new SavingsAccount(S&quot;Denise Smith&quot;, 100.00, 25); sa->Display; </li> <li> Add the following code to call public methods in SavingsAccount or in Account: sa->Credit(100); sa->Debit(180); sa->ChangeName(S&quot;Samantha Smith&quot;); sa->Display; Console::WriteLine(S&quot;Bank Charge: {0}&quot;,(sa->CalculateBankCharge).ToString); </li> <li>Build the application.</li> <li> 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 </li></ol>
 * 1) include &quot;SavingsAccount.h&quot; </li>

back to the top

<div class="references_section">