How to use inheritance in Visual C++

For a Microsoft Visual C# .NET version of this article, see
307205 .
For a Microsoft Visual Basic .NET version of this article, see
307222 .

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

  1. 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:
    1. Under Project Types, click Visual C++ Projects.
    2. Under Templates, click Console Application (.NET).




    In Visual C++ 2005, follow these steps:


    1. Under Project Types, click Visual C++.
    2. Under Templates, click CLR Console Application.
  2. Save the project.
back to the top

Create an Abstract Base Class and a Derived Class

  1. In Solution Explorer, switch to the Class View. To do this, click Class View on the View menu.
  2. Right-click the UseInheritance project, point to Add, and then click
    Add Class.

    Note In Visual C++ 2005, click Class, not Add Class.
  3. 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.
  4. 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:

    1. Click Project, and then click ProjectName Properties.

      Note ProjectName represents the name of the project.
    2. Expand Configuration Properties, and then click General.

    3. 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:
    /clr (Common Language Runtime Compilation)
    http://msdn2.microsoft.com/en-us/library/k8d11d4s.aspx
  5. Repeat steps 1-3 to add the SavingsAccount generic C++ class.
  6. 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 top

Write Code for the Base Class

  1. Open the Account.h file
  2. Use the mscorlib.dll as follows:
    #using <mscorlib.dll> // You must use this code to take advantage of the .NET Framework.
  3. 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
  4. 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.
  5. Override the Account constructor to initialize these fields:
    public :
    Account(String *szName, double bal)
    {
    this->name = szName;
    this->balance = bal;
    }
  6. 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;
    }
  7. 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());
    }
  8. 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 top

Write Code for the Derived Class

  1. Open the SavingsAccount.h file.
  2. Add a field to the SavingsAccount class:
    private:
    double minBalance; // If the balance drops below minBalance,
    // the bank charges a fee on the account.
  3. 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.
    }
  4. 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());
    }
  5. 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 top

Verify That It Works

  1. Open the code for the UseInheritance.cpp file in the Code View window. Add the following code to UseInheritance.cpp:
    #include "SavingsAccount.h"
  2. 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();
  3. 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());
  4. Build the application.
  5. 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 top

References

For 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
Propriedades

ID do Artigo: 815670 - Última Revisão: 14 de nov de 2007 - Revisão: 1

Comentários