< Class, Object & Unmanaged Code 1 | Main | Class, Object & Unmanaged Code 3 >


 

 

Object-Oriented Programming:

Class, Object and Unmanaged Code 2

 

 

What do we have in this page?

 

  1. Implementing a Class in a Source File

  2. Creating and Destroying Objects

 

 

Implementing a Class in a Source File

 

In this exercise, you will implement the CreditCardAccount class in a source file.

 

1.   Continue using the project from the previous exercise.

2.   Select the Project menu item, and then choose Add New Item.

3.   In the Add New Item dialog box, select the template Source File (.cpp). In the Name field, type CreditCardAccount.cpp and click Add. Visual C++/Studio .NET creates an empty source file.

 

C++ .Net - Adding new source file for the class definition or implementation to the existing project

 

4.        Add two #include statements at the start of the file, as follows:

#include "stdafx.h"

#include "CreditCardAccount.h"

The file stdafx.h is a header file that can include other standard header files; you include stdafx.h at the start of every source file in your project.

// stdafx.h : include file for standard system include files,

// or project specific include files that are used frequently, but

// are changed infrequently

//

 

#pragma once

 

// TODO: reference additional headers your program requires here

CreditCardAccount.h contains the class definition for CreditCardAccount. You include this header file here so that the compiler can check your implementation of the CreditCardAccount class.

5.        Add the following code so that you can use classes and data types defined in the System namespace:

// #using <mscorlib.dll> // for older version

using namespace System;

The #using <mscorlib.dll> preprocessor directive imports the Microsoft intermediate language (MSIL) file mscorlib.dll so that you can use managed data and managed constructs defined in this DLL file. For the new version of the .Net Framework, this preprocessor directive automatically included so we commented it out. The using namespace System statement enables you to use classes and data types defined in the System namespace. Specifically, you will use the Console class to display messages on the console.

6.        Implement the CreditCardAccount::MakePurchase member function as follows:

 

bool CreditCardAccount::MakePurchase(double amount)

{

    if (currentBalance + amount > creditLimit)

    {

        return false;

    }

    else

    {

        currentBalance += amount;

        return true;

    }

}

This function is called when the card owner attempts to make a purchase using the credit card. The amount parameter indicates the amount of the purchase. The function tests whether the purchase would exceed the creditLimit data member and returns false in this case. Otherwise, the function adds the amount to the currentBalance data member and returns true.

Note: Member functions have unrestricted access to all the members in the class, including private members.

7.        Implement the CreditCardAccount::MakeRepayment member function as follows:

void CreditCardAccount::MakeRepayment(double amount)

{

    currentBalance -= amount;

}

This function allows the user to pay off some or all of the outstanding balance.

8.        Implement the CreditCardAccount::PrintStatement member function as follows:

void CreditCardAccount::PrintStatement()

{

    Console::Write("Account number: ");

    Console::WriteLine(accountNumber);

 

    Console::Write("Current balance: ");

    Console::WriteLine(currentBalance);

}

This function displays information about the current state of the account. A complete code for this part is shown below.

// CreditCardAccount.cpp

#include "stdafx.h"

#include "CreditCardAccount.h"

 

// #using <mscorlib.dll> // for older version

using namespace System;

 

bool CreditCardAccount::MakePurchase(double amount)

{

    if (currentBalance + amount > creditLimit)

    {

        return false;

    }

    else

    {

        currentBalance += amount;

        return true;

    }

}

 

void CreditCardAccount::MakeRepayment(double amount)

{

    currentBalance -= amount;

}

 

void CreditCardAccount::PrintStatement()

{

    Console::Write("Account number: ");

    Console::WriteLine(accountNumber);

    Console::Write("Current balance: ");

    Console::WriteLine(currentBalance);

}

9.        Build the program, and fix any compiler errors.

 

Creating and Destroying Objects

 

Once you have defined and implemented a class, you are ready to start creating and destroying objects. The way you create and destroy an object in Microsoft Visual C++ depends on whether the class is a managed class or an unmanaged class. In this module, we will consider only unmanaged classes, managed classes are discussed in more detail in other module. The following code shows how to create an object, call its public member functions, and delete the object when it is no longer needed:

// Declare a pointer

CreditCardAccount  * myAccount;

// Create a new CreditCardAccount object

myAccount = new CreditCardAccount;

// Use -> operator to invoke member functions

myAccount->MakePurchase(100);

myAccount->MakeRepayment(70);

myAccount->PrintStatement();

...

// Explicitly delete object when not needed

delete myAccount;

The new operator creates a new object of the CreditCardAccount class and returns a pointer to this new object. The pointer is used with the -> operator to invoke various member functions on the new object. When the object is no longer needed, you must explicitly destroy the object using the delete operator. If you forget to delete an object of an unmanaged class, the garbage collector doesn’t help you out. The object remains allocated in memory, which constitutes a memory leak and is one of the most common problems in traditional C++ applications. Another common error is to delete an object too soon. If you try to use the object after it has been deleted, your program will cause a run-time exception.

 

In this exercise, you will create a new CreditCardAccount object, invoke its member functions, and delete the object when it is no longer required.

 

1.        Continue using the project from the previous exercise.

2.        If Solution Explorer isn’t visible, select the View menu and then choose Solution Explorer.

3.        In the Solution Explorer window, find the source file CreditOrganizer.cpp. Double-click this file to display it in the editor.

4.        Just after the #include "stdafx.h" line, add another #include directive, as follows:

#include "CreditCardAccount.h"

This line enables you to create and use CreditCardAccount objects in this source file.

5.        Delete the Hello World code and add the following code to the main() function:

// Declare a pointer

CreditCardAccount * myAccount;

// Create a new CreditCardAccount object

myAccount = new CreditCardAccount;

// Use -> operator to invoke member functions

myAccount->MakePurchase(1000);

myAccount->MakeRepayment(700);

myAccount->PrintStatement();

// Explicitly delete object when not needed

delete myAccount;

C++ .Net unmanaged class programming - Adding source code to manipulate the class (object) in the main program file  

 

6.   Build the program, and fix any compiler errors.

7.   Run the program by pressing Ctrl+F5. The program creates a CreditCardAccount object, makes a purchase and a repayment, and prints a statement. However, the statement displays seemingly random numbers for the current balance and account number.

 

C++ .Net - console program output sample

 

The reason for this result is that the CreditCardAccount object is not initialized when it’s created. The data members in the object take on whatever values happen to be in memory where the object is located. To resolve this problem, you can define a constructor in the CreditCardAccount class. The constructor will initialize new objects when they’re created. You can also define a destructor in the class to tidy up objects just before they are destroyed.

 

 

 

 

Part 1 | Part 2 | Part 3 | Part 4 | Part 5

 


 

< Class, Object & Unmanaged Code 1 | Main | Class, Object & Unmanaged Code 3 >