Lessons Home

Classes and Functions

 

Combinations

In order to perform the various assignments it receives, the computer manipulates objects created in a program. In most significant applications, one object is not enough to accomplish a whole purpose. As we have learned that the use of one variable in a program is unrealistic, we can also combine various objects to create a more realistic and complete application.

There are various techniques used to mix objects in a program. To imitate the idea of combining different variables in a program, we will start by passing an object as a function argument, then we will be using various objects in the same program.

Objects and Functions

One of the most regular operations you will perform in your program consists of mixing objects and functions. Fortunately, C++ allows you to pass an object to a function or to return an object from a function. An object you use in a program can come from any source: an object built-in the operating system (part of the Win32 library), an object shipped with Borland C++ Builder, an object that is part of the C++ language, or one that you create.

The first thing you should do is create an object, unless you are using an existing one. Let’s build a conic tent. It is recognized by its radius, its height, the base area, and the area occupied by the texture. Our tent will look “long”, this is because I purposely included most of the techniques or features of building an object as we have learned so far. 

The header file creates a TCone object made of three constructors and a destructor. Since we will have private dimensions, we use get and set methods to take care of transactions between the object and the external world. We will also perform appropriate calculations.

Header File: Cone.h

//---------------------------------------------------------------------------



#ifndef ConeH

#define ConeH

//---------------------------------------------------------------------------

struct TCone

{

public:

    TCone();                     // Default constructor

    TCone(double r, double h);   // Constructor to initialize

    TCone(const TCone& c);       // Copy constructor

    ~TCone();                    // Destructor

    void setRadius(const double r) { Radius = r; }

    void setHeight(const double h) { Height = h; }

    double getRadius() const { return Radius; }

    double getHeight() const { return Height; }

    double Base() const;

    double TextureArea() const;

    double Volume() const;

private:

    double Radius;

    double Height;

};

//---------------------------------------------------------------------------

#endif

The source file is used to initialize the object (its member variables) and to perform the necessary calculations involved with the object.

Source File: Cone.cpp

//---------------------------------------------------------------------------

#include <math>

using namespace std;



#include "Cone.h"

//---------------------------------------------------------------------------



//const double PI = 3.1415926535;

//---------------------------------------------------------------------------

TCone::TCone()

    : Radius(0.00), Height(0.00)

{

    //TODO: Add your source code here

}

//---------------------------------------------------------------------------

TCone::TCone(double r, double h)

    : Radius(r), Height(h)

{

    //TODO: Add your source code here

}

//---------------------------------------------------------------------------

TCone::TCone(const TCone& c)

    : Radius(c.Radius), Height(c.Height)

{

    //TODO: Add your source code here

}

//---------------------------------------------------------------------------

TCone::~TCone()

{

    //TODO: Add your source code here

}

//---------------------------------------------------------------------------

double TCone::Base() const

{

    // The area of the base of the cone

    return Radius * Radius * M_PI;

}

//---------------------------------------------------------------------------

double TCone::TextureArea() const

{

    // The area covered by the tissue that covers the tent

    double Radius2 = Radius * Radius;

    double Height2 = Height * Height;

    double SlantHeight = sqrt(Radius2 + Height2);

    return M_PI * Radius * SlantHeight;

}

//---------------------------------------------------------------------------

double TCone::Volume() const

{

    // The interior volume available for inhabiting the tent

    return (M_PI * Radius * Radius * Height) / 3;

}

//---------------------------------------------------------------------------

Once the object is built, you can call it from another function. As we have done with the main() function, you can call an object “as is” using the default constructor, which itself has the responsibility of using default values for its members:

Source File: Main.cpp

//---------------------------------------------------------------------------

#include <iostream>

using namespace std;

#include "Cone.h"

//---------------------------------------------------------------------------

int main(int argc, char* argv[])

{

    TCone Conic;



    cout << "A tent with default dimensions";

    cout << "\nRadius: " << Conic.getRadius();

    cout << "\nHeight: " << Conic.getHeight();

    cout << "\nBase Area: " << Conic.Base();

    cout << "\nTexture Area: " << Conic.TextureArea() << "\n";



    return 0;

}

//---------------------------------------------------------------------------

The program produces:

A tent with default dimensions

Radius: 0

Height: 0

Base Area: 0

Texture Area: 0



In the same way you can provide values for the object, using the right constructor or the right method:

Source File: Main.cpp

//---------------------------------------------------------------------------

#include <iostream>

using namespace std;

#include "Cone.h"

//---------------------------------------------------------------------------

int main(int argc, char* argv[])

{

    TCone Tone(25.55, 32.95);

    cout << "A tent with default dimensions";

    cout << "\nRadius:       " << Tone.getRadius();

    cout << "\nHeight:       " << Tone.getHeight();

    cout << "\nBase Area:    " << Tone.Base();

    cout << "\nTexture Area: " << Tone.TextureArea() << "\n";



    return 0;

}

//---------------------------------------------------------------------------

With an object as complete as our cone, you can let the user provide the dimensions for the tent:

Source File: Main.cpp

//---------------------------------------------------------------------------

#include <iostream>

using namespace std;

#include "Cone.h"

//---------------------------------------------------------------------------

int main(int argc, char* argv[])

{

    TCone Camper;

    double r, h;



    cout << "Specify the dimensions of the tent\n";

    cout << "Radius: ";

    cin >> r;

    cout << "Radius: ";

    cin >> h;



    Camper.setRadius(r);

    Camper.setHeight(h);

    

    cout << "\nA tent with user-defined dimensions";

    cout << "\nRadius:       " << Camper.getRadius();

    cout << "\nHeight:       " << Camper.getHeight();

    cout << "\nBase Area:    " << Camper.Base();

    cout << "\nTexture Area: " << Camper.TextureArea() << "\n";



    return 0;

}

//---------------------------------------------------------------------------

Which would produce, for example:

Specify the dimensions of the tent

Radius: 7.24

Radius: 4.88



A tent with user-defined dimensions

Radius:       7.24

Height:       4.88

Base Area:    164.675

Texture Area: 198.59



 

The Starting Object

  1. Start your programming environment if you didn’t yet.
  2. Create a C++ application and save the project in a folder called ROSH1. Save the starting unit as Main.cpp and the project as ROSH
  3. Create a new unit and save it as Students in the ROSH1 folder
  4. Change the Students.h file as follows:
     
    //---------------------------------------------------------------------------
    
    #ifndef StudentsH
    
    #define StudentsH
    
    #include <iostream>
    
    //---------------------------------------------------------------------------
    
    class TStudent
    
    {
    
    public:
    
        TStudent();
    
        TStudent(string fn, string ln, int d, int m, int y);
    
        ~TStudent();
    
        string getFirstName() { return FirstName; }
    
        string getLastName() { return LastName; }
    
        int getDayOfBirth() { return DayOfBirth; }
    
        int getMonthOfBirth() { return MonthOfBirth; }
    
        int getYearOfBirth() { return YearOfBirth; }
    
    private:
    
        string FirstName;
    
        string LastName;
    
        int DayOfBirth;
    
        int MonthOfBirth;
    
        int YearOfBirth;
    
    };
    
    //---------------------------------------------------------------------------
    
    #endif
  5. Change the Students.cpp file as follows:
     
    //---------------------------------------------------------------------------
    
    
    
    using namespace std;
    
    
    
    #include "Students.h"
    
    //---------------------------------------------------------------------------
    
    
    
    TStudent::TStudent()
    
    {
    
        FirstName = "John";
    
        LastName = "Doe";
    
        DayOfBirth = 1;
    
        MonthOfBirth = 1;
    
        YearOfBirth = 1990;
    
    }
    
    //---------------------------------------------------------------------------
    
    TStudent::TStudent(string fn, string ln, int d, int m, int y)
    
        : FirstName(fn), LastName(ln),
    
          DayOfBirth(d), MonthOfBirth(m), YearOfBirth(y)
    
    {
    
        
    
    }
    
    //---------------------------------------------------------------------------
    
    TStudent::~TStudent()
    
    {
    
        //TODO: Add your source code here
    
    }
    
    //---------------------------------------------------------------------------
  6. Implement the Main.cpp file as follows:
     
    //---------------------------------------------------------------------------
    
    #include <iostream>
    
    using namespace std;
    
    #include "Students.h"
    
    //---------------------------------------------------------------------------
    
    
    
    
    
    int main(int argc, char* argv[])
    
    {
    
        TStudent St;
    
    
    
        cout << "Student with default values";
    
        cout << "\nFull Name: " << St.getFirstName()
    
             << " " << St.getLastName();
    
        cout << "\nDate of Birth: " << St.getDayOfBirth()
    
             << "/" << St.getMonthOfBirth()
    
             << "/" << St.getYearOfBirth();
    
        
    
        return 0;
    
    }
    
    //---------------------------------------------------------------------------
  7. To test the program, press F9:
     
    Student with default values
    
    Full Name: John Doe
    
    Date of Birth: 1/1/1990
    
    
    
    
  8. Return to your programming environment.
  9. To test the program with other values, change the Main.cpp file as follows:
     
    //---------------------------------------------------------------------------
    
    #include <iostream>
    
    using namespace std;
    
    #include "Students.h"
    
    //---------------------------------------------------------------------------
    
    
    
    int main(int argc, char* argv[])
    
    {
    
        TStudent St("Jeannette", "Smith", 12, 5, 1988);
    
    
    
        cout << "Student Information";
    
        cout << "\nFull Name: " << St.getFirstName()
    
             << " " << St.getLastName();
    
        cout << "\nDate of Birth: " << St.getDayOfBirth()
    
             << "/" << St.getMonthOfBirth()
    
             << "/" << St.getYearOfBirth();
    
        
    
        return 0;
    
    }
    
    //---------------------------------------------------------------------------
  10. Test the program
  11. Return to your programming environment.
  12. To let the user provide the values of an object, you can request these values from the user and fill out the object with those values. To see an example, change the Main.cpp file as follows:
     
    //---------------------------------------------------------------------------
    
    #include <iostream>
    
    using namespace std;
    
    #include "Students.h"
    
    //---------------------------------------------------------------------------
    
    int main(int argc, char* argv[])
    
    {
    
        string FN, LN;
    
        int Day, Month, Year;
    
        cout << "Enter the student's information\n";
    
        cout << "First Name: ";
    
        cin >> FN;
    
        cout << "Last Name: ";
    
        cin >> LN;
    
        cout << "Day of Birth: ";
    
        cin >> Day;
    
        cout << "Month of Birth: ";
    
        cin >> Month;
    
        cout << "Year of Birth: ";
    
        cin >> Year;
    
    
    
        TStudent St(FN, LN, Day, Month, Year);
    
    
    
        cout << "\nStudent Information";
    
        cout << "\nFull Name: " << St.getFirstName()
    
             << " " << St.getLastName();
    
        cout << "\nDate of Birth: " << St.getDayOfBirth()
    
             << "/" << St.getMonthOfBirth()
    
             << "/" << St.getYearOfBirth();
    
        
    
        return 0;
    
    }
    
    //---------------------------------------------------------------------------
  13. Test the program by press F9. Here is an example:
     
    Enter the student's information
    
    First Name: Gregory
    
    Last Name: Ballack
    
    Day of Birth: 22
    
    Month of Birth: 6
    
    Year of Birth: 1988
    
    
    
    Student Information
    
    Full Name: Gregory Ballack
    
    Date of Birth: 22/6/1988
    
    
    
    
  14. Return to your programming environment
  15. Writing values to an object allows the user to control the object. That’s why set methods are very valuable. To provide set methods, change the header file of the TStudents object as follows:

    Header File: Students.h
    //---------------------------------------------------------------------------
    
    #ifndef StudentsH
    
    #define StudentsH
    
    #include <iostream>
    
    //---------------------------------------------------------------------------
    
    class TStudent
    
    {
    
    public:
    
        TStudent();
    
        TStudent(string fn, string ln, int d, int m, int y);
    
        ~TStudent();
    
        void setFirstName(string f) { FirstName = f; }
    
        string getFirstName() { return FirstName; }
    
        void setLastName(string l) { LastName = l; }
    
        string getLastName() { return LastName; }
    
        void setDayOfBirth(int d) { DayOfBirth = d; }
    
        int getDayOfBirth() { return DayOfBirth; }
    
        void setMonthOfBirth(int m) { MonthOfBirth = m; }
    
        int getMonthOfBirth() { return MonthOfBirth; }
    
        void setYearOfBirth(int y) { YearOfBirth = y; }
    
        int getYearOfBirth() { return YearOfBirth; }
    
    
    
    private:
    
        string FirstName;
    
        string LastName;
    
        int DayOfBirth;
    
        int MonthOfBirth;
    
        int YearOfBirth;
    
    };
    
    //---------------------------------------------------------------------------
    
    #endif
  16. To request values of the Tstudents object, change the Main.cpp file as follows:

    Source File: Main.cpp
    //---------------------------------------------------------------------------
    
    #include <iostream>
    
    using namespace std;
    
    #include "Students.h"
    
    //---------------------------------------------------------------------------
    
    int main(int argc, char* argv[])
    
    {
    
        string FN, LN;
    
        int Day, Month, Year;
    
        TStudent St;
    
    
    
        cout << "Enter the student's information\n";
    
        cout << "First Name: ";
    
        cin >> FN;
    
        cout << "Last Name: ";
    
        cin >> LN;
    
        cout << "Day of Birth: ";
    
        cin >> Day;
    
        cout << "Month of Birth: ";
    
        cin >> Month;
    
        cout << "Year of Birth: ";
    
        cin >> Year;
    
    
    
        St.setFirstName(FN);
    
        St.setLastName(LN);
    
        St.setDayOfBirth(Day);
    
        St.setMonthOfBirth(Month);
    
        St.setYearOfBirth(Year);
    
    
    
        cout << "\nStudent Information";
    
        cout << "\nFull Name: " << St.getFirstName()
    
             << " " << St.getLastName();
    
        cout << "\nDate of Birth: " << St.getDayOfBirth()
    
             << "/" << St.getMonthOfBirth()
    
             << "/" << St.getYearOfBirth();
    
        
    
        return 0;
    
    }
    
    //---------------------------------------------------------------------------
  17. To test the program, press F9. Here is an example:
     
    Enter the student's information
    
    First Name: Juan
    
    Last Name: Gomez
    
    Day of Birth: 2
    
    Month of Birth: 2
    
    Year of Birth: 1991
    
    
    
    Student Information
    
    Full Name: Juan Gomez
    
    Date of Birth: 2/2/1991
    
    
    
    
  18. Return to your programming environment

An object as an Argument

After creating an object, it becomes a data type, sometimes referred to as a programmer defined data type. As an identifier, you can declare an object inside of a function and use it. That is what we have done so far when using objects inside of the main() function.

There are two techniques used to involve an object with a function. You can pass a member of an object as argument to a function, or you can pass the whole object as an argument. When passing an object as a parameter, you should be familiar with the construction of the object. Know its members and which ones you need to use. The code completion feature is highly useful in this circumstance.

Instead of displaying the characteristics of the tent in the main() function, we can use an external function to perform that assignment.

Source File: Main.cpp

//---------------------------------------------------------------------------

#include <iostream>

using namespace std;

#include "Cone.h"

//---------------------------------------------------------------------------

void ShowTent(TCone c)

{

    cout << "Characteristics of this tent";

    cout << "\nRadius: " << c.getRadius();

    cout << "\nHeight: " << c.getHeight();

    cout << "\nBase Area: " << c.Base();

    cout << "\nTexture Area: " << c.TextureArea() << "\n";

}

//---------------------------------------------------------------------------

int main(int argc, char* argv[])

{

    TCone Tent;

    ShowTent(Tent);



    return 0;

}

//---------------------------------------------------------------------------

Even if you let the user provide the values of the object, after constructing such an object, you can pass it to a function that would manipulate it, including displaying its characteristics:

Source File: Main.cpp

//---------------------------------------------------------------------------

#include <iostream>

#include <iomanip>

using namespace std;

#include "Cone.h"

//---------------------------------------------------------------------------

void ShowTent(TCone c)

{

    cout << "\nCharacteristics of this tent";

    cout << setiosflags(ios::fixed) << setprecision(2);

    cout << "\nRadius:       " << c.getRadius();

    cout << "\nHeight:       " << c.getHeight();

    cout << "\nBase Area:    " << c.Base();

    cout << "\nTexture Area: " << c.TextureArea() << "\n";

}

//---------------------------------------------------------------------------

int main(int argc, char* argv[])

{

    TCone Tent;

    double r, h;



    cout << "Specify the dimensions of the tent\n";

    cout << "Radius: ";

    cin >> r;

    cout << "Height: ";

    cin >> h;



    Tent.setRadius(r);

    Tent.setHeight(h);

    ShowTent(Tent);



    return 0;

}

//---------------------------------------------------------------------------

Here is an example of running the program:

Specify the dimensions of the tent

Radius: 10.24

Height: 6.84



Characteristics of this tent

Radius:       10.24

Height:       6.84

Base Area:    329.42

Texture Area: 396.15



 

Using an Object as an Argument

  1. To use an object as argument, change the Main.cpp file as follows:
     
    //---------------------------------------------------------------------------
    
    #include <iostream>
    
    using namespace std;
    
    #include "Students.h"
    
    //---------------------------------------------------------------------------
    
    int main(int argc, char* argv[])
    
    {
    
        string FN, LN;
    
        int Day, Month, Year;
    
        void ShowStudent(TStudent s);
    
    
    
        cout << "Enter the student's information\n";
    
        cout << "First Name: "; cin >> FN;
    
        cout << "Last Name: "; cin >> LN;
    
        cout << "Day of Birth: "; cin >> Day;
    
        cout << "Month of Birth: "; cin >> Month;
    
        cout << "Year of Birth: "; cin >> Year;
    
    
    
        TStudent St(FN, LN, Day, Month, Year);
    
        ShowStudent(St);
    
    
    
        return 0;
    
    }
    
    //---------------------------------------------------------------------------
    
    void ShowStudent(TStudent s)
    
    {
    
        cout << "\nStudent Registration";
    
        cout << "\nFull Name: "
    
             << s.getFirstName() << " " << s.getLastName();
    
        cout << "\nDate of Birth: " << s.getDayOfBirth() << "/"
    
             << s.getMonthOfBirth() << "/" << s.getYearOfBirth();
    
    }//---------------------------------------------------------------------------
  2. To test the program, press F9. Here is an example:
     
    Enter the student's information
    
    First Name: Joan
    
    Last Name: Lucent
    
    Day of Birth: 18
    
    Month of Birth: 4
    
    Year of Birth: 1986
    
    
    
    Student Registration
    
    Full Name: Joan Lucent
    
    Date of Birth: 18/4/1986
    
    
    
    
  3. Return to your programming environment

Objects and their External Interaction

 

Returning an Object

As a data type, you can use an object as returning value of a function. The issue this time is a little different. When returning an object, you should be familiar with the construction of the object, especially its constructorr. Since you will mostly return an object as complete as possible, the returned variable is a constructor. Therefore, when building the object inside of the function, make sure that the object can be used as a variable. Ask yourself if the object you are returning can be passed an argument to another function. Can it be used to display the complete properties of the object?

As opposed to requesting the dimensions of the tent from the main() function, we will use an external function to take care of that so that when the object is returned, we will trust that it can be used by another part of the program.

Source File: Main.cpp

//---------------------------------------------------------------------------

#include <iostream>

#include <iomanip>

using namespace std;

#include "Cone.h"

//---------------------------------------------------------------------------





void Exit()

{

    

    

}

//---------------------------------------------------------------------------

void ShowTent(TCone c)

{

    cout << "\nCharacteristics of this tent";

    cout << setiosflags(ios::fixed) << setprecision(2);

    cout << "\nRadius:       " << c.getRadius();

    cout << "\nHeight:       " << c.getHeight();

    cout << "\nBase Area:    " << c.Base();

    cout << "\nTexture Area: " << c.TextureArea() << "\n";

}

//---------------------------------------------------------------------------

TCone ObtainDimensions()

{

    double r, h;



    cout << "Specify the dimensions of the tent\n";

    cout << "Radius: "; cin >> r;

    cout << "Radius: "; cin >> h;



    return TCone::TCone(r, h); // Returning the constructor

}

//---------------------------------------------------------------------------

int main(int argc, char* argv[])

{

    TCone Tent;



    Tent = ObtainDimensions();

    ShowTent(Tent);



    Exit();

    return 0;

}

//---------------------------------------------------------------------------

An example of running the program would produce:

Specify the dimensions of the tent

Radius: 8.44

Radius: 5.26



Characteristics of this tent

Radius:       8.44

Height:       5.26

Base Area:    223.79

Texture Area: 263.69



Another version of the ObainDimensions() function would consist of assigning the values of the member variables of the object to the right access methods:

Source File: Main.cpp

//---------------------------------------------------------------------------

TCone ObtainDimensions()

{

    double r, h;

    TCone Tonic;



    cout << "Specify the dimensions of the tent\n";

    cout << "Radius: "; cin >> r;

    cout << "Height: "; cin >> h;



    Tonic.setRadius(r);

    Tonic.setHeight(h);

    return Tonic;

}

//---------------------------------------------------------------------------

As another technique, you can first build the object by assembling the necessary member variables. Once the variables are gathered, you build an object based on those and return such an object from the function. Here is an example:

Source File: Main.cpp

//---------------------------------------------------------------------------

TCone ObtainDimensions()

{

    double r, h;



    cout << "Specify the dimensions of the tent\n";

    cout << "Radius: "; cin >> r;

    cout << "Height: "; cin >> h;



    TCone Copper(r, h);

    return Copper;

}

//---------------------------------------------------------------------------

Any of these techniques should allow you to return the desired object from a function and be able to use that object somewhere else, including displaying its properties using another function:

Specify the dimensions of the tent

Radius: 18.12

Height: 10.26



Characteristics of this tent

Radius:       18.12

Height:       10.26

Base Area:    1031.49

Texture Area: 1185.37



 

Returning an Object From a Function

  1. To apply an example of returning an object, change the Main.cpp file as follows:
     
    //---------------------------------------------------------------------------
    
    #include <iostream>
    
    using namespace std;
    
    #include "Students.h"
    
    //---------------------------------------------------------------------------
    
    
    
    
    
    
    
    
    
    int main(int argc, char* argv[])
    
    {
    
        TStudent Stud;
    
        TStudent Register();
    
        void ShowStudent(TStudent Grade1);
    
    
    
        Stud = Register();
    
        ShowStudent(Stud);
    
    
    
    
    
        
    
        
    
        
    
        return 0;
    
    }
    
    //---------------------------------------------------------------------------
    
    void ShowStudent(TStudent s)
    
    {
    
        cout << "\nStudent Registration";
    
        cout << "\nFull Name: "
    
             << s.getFirstName() << " " << s.getLastName();
    
        cout << "\nDate of Birth: " << s.getDayOfBirth() << "/"
    
             << s.getMonthOfBirth() << "/" << s.getYearOfBirth();
    
    }
    
    //---------------------------------------------------------------------------
    
    TStudent Register()
    
    {
    
        string FN, LN;
    
        int Day, Month, Year;
    
        TStudent s;
    
    
    
        cout << "Enter the student's information\n";
    
        cout << "First Name: "; cin >> FN;
    
        cout << "Last Name: "; cin >> LN;
    
        cout << "Day of Birth: "; cin >> Day;
    
        cout << "Month of Birth: "; cin >> Month;
    
        cout << "Year of Birth: "; cin >> Year;
    
    
    
        s.setFirstName(FN);
    
        s.setLastName(LN);
    
        s.setDayOfBirth(Day);
    
        s.setMonthOfBirth(Month);
    
        s.setYearOfBirth(Year);
    
    
    
        return s;
    
    }
    
    //---------------------------------------------------------------------------
  2. Press F9 to test the program. Here is an example:
     
    Enter the student's information
    
    First Name: Jarrel
    
    Last Name: Jeremies
    
    Day of Birth: 2
    
    Month of Birth: 4
    
    Year of Birth: 1991
    
    
    
    Student Registration
    
    Full Name: Jarrel Jeremies
    
    Date of Birth: 2/4/1991
    
    
    
    
  3. Return to your programming environment

 Passing an Object by Reference

Since an object is a data type, it enjoys the features of the other, regular, variables. For example, instead of returning an object from a function, when this is not possible because of some circumstances, you can pass an object by reference. Like another variable, when an object is passed by reference, any alteration made on the object will be kept when the function exists. This feature allows you to declare a function as void but return a completely built object.

To pass an object by reference, use the ampersand between its name and the name of the argument inside of the function parentheses:

Source File: Main.cpp

//---------------------------------------------------------------------------

#include <iostream>

#include <iomanip>

using namespace std;

#include "Cone.h"

//---------------------------------------------------------------------------





void Exit()

{

    

    

}

//---------------------------------------------------------------------------

void ShowTent(TCone c)

{

    cout << "\nCharacteristics of this tent";

    cout << setiosflags(ios::fixed) << setprecision(2);

    cout << "\nRadius:       " << c.getRadius();

    cout << "\nHeight:       " << c.getHeight();

    cout << "\nBase Area:    " << c.Base();

    cout << "\nTexture Area: " << c.TextureArea() << "\n";

}

//---------------------------------------------------------------------------

void ObtainDimensions(TCone& Tone)

{

    double r, h;



    cout << "Specify the dimensions of the tent\n";

    cout << "Radius: "; cin >> r;

    cout << "Radius: "; cin >> h;



    Tone.setRadius(r);

    Tone.setHeight(h);

}

//---------------------------------------------------------------------------

int main(int argc, char* argv[])

{

    TCone Tent;



    ObtainDimensions(Tent);

    ShowTent(Tent);



    Exit();

    

    return 0;

}

//---------------------------------------------------------------------------

Here is example of running the program:

Specify the dimensions of the tent

Radius: 5.12

Radius: 3.84



Characteristics of this tent

Radius:       5.12

Height:       3.84

Base Area:    82.35

Texture Area: 102.94



 

Passing an Object by Reference

  1. To pass an object as reference, change the Main.cpp file as follows:
     
    //---------------------------------------------------------------------------
    
    #include <iostream>
    
    using namespace std;
    
    #include "Students.h"
    
    //---------------------------------------------------------------------------
    
    
    
    
    
    
    
    int main(int argc, char* argv[])
    
    {
    
        TStudent Stud;
    
        void Register(TStudent&);
    
        void ShowStudent(TStudent Grade1);
    
    
    
        Register(Stud);
    
        ShowStudent(Stud);
    
    
    
        
    
        
    
        
    
        return 0;
    
    }
    
    //---------------------------------------------------------------------------
    
    void Register(TStudent& S)
    
    {
    
        string FN, LN;
    
        int Day, Month, Year;
    
    
    
        cout << "Enter the student's information\n";
    
        cout << "First Name: "; cin >> FN;
    
        cout << "Last Name: "; cin >> LN;
    
        cout << "Day of Birth: "; cin >> Day;
    
        cout << "Month of Birth: "; cin >> Month;
    
        cout << "Year of Birth: "; cin >> Year;
    
    
    
        S.setFirstName(FN);
    
        S.setLastName(LN);
    
        S.setDayOfBirth(Day);
    
        S.setMonthOfBirth(Month);
    
        S.setYearOfBirth(Year);
    
    }
    
    //---------------------------------------------------------------------------
    
    void ShowStudent(TStudent s)
    
    {
    
        cout << "\nStudent Registration";
    
        cout << "\nFull Name: "
    
             << s.getFirstName() << " " << s.getLastName();
    
        cout << "\nDate of Birth: " << s.getDayOfBirth() << "/"
    
             << s.getMonthOfBirth() << "/" << s.getYearOfBirth();
    
    }
    
    //---------------------------------------------------------------------------
  2. Test the program and return to your programming environment

Friend Functions of a Class

Good programming techniques dictate that you should hide the variables used to store data of a class. This is done by declaring the member variables in the private section. Once a variable is hidden like that, only the members of the same class have access to it. The C++ language provides an alternative to this problem. Although you can still hide your variables, you can create special functions that have a “priviledged” access to the members of the private section of a class. These functions are not members of the class, they are just granted special access to the hidden member variables. Such functions are qualified as friends.

To declare a friend function, start with the friend keyword, followed by the return value, followed by the name of the function, its parentheses, and possibly the necessary arguments. Since a friend is not a function member of the object, you should provide access to the object, one way or another. When a function has been declared as a friend of a class, the class grants and controls the friendship.

The friend keyword is used only when declaring the friendly function. When defining the function, proceed as if it were a regularly declared function, omitting the friend keyword. Because friend functions are given special access, they can be declared anywhere in the class; but a good habit is to position them on top of the object just under the opening curly braket. This allow the compiler, you, and anybody who reads your code to have the list of friends of the class.

Here is a starting example. The Item class has two member variables that represent the quantity and the unit price. Both members are hidden in the private section, which means they cannot be seen outside of the class. Instead of creating a TotalPrice() member function, a friend function is declared so it can access the private members of the object:

//---------------------------------------------------------------------------

#include <iostream>

using namespace std;



//---------------------------------------------------------------------------





class TForSale

{

    friend double TotalPrice(TForSale i);

public:

    TForSale(int q = 0, double p = 0.00);

private:

    int Qty;

    double UnitPrice;

};

//---------------------------------------------------------------------------

TForSale::TForSale(int Quantity, double Price)

    : Qty(Quantity), UnitPrice(Price)

{

}

//---------------------------------------------------------------------------

double TotalPrice(TForSale i)

{

    return i.Qty * i.UnitPrice;

}

//---------------------------------------------------------------------------

int main(int argc, char* argv[])

{

    TForSale item(12, 0.99);



    cout << "Total Price: $" << TotalPrice(item) << endl;



    

    

    return 0;

}

//---------------------------------------------------------------------------

An example of running the program would produce:

Total Price: $11.88



Although the above example comports only one function, an object can have as many friends as you see fit. For example, you can create a TTriangle object that has a Base and a Height private members, then declare two friend functions, one to calculate the perimeter and the other to calculate the area. The previous program was made of only one file. This time, you can separate the interface and the implementations in two files.

The object definition could appear as follows:

//---------------------------------------------------------------------------



#ifndef TriangleH

#define TriangleH

//---------------------------------------------------------------------------

struct TTriangle

{

    friend double Perimeter(TTriangle Tri);

    friend double Area(TTriangle Tri);



public:

    TTriangle(double B = 0.00, double H = 0.00);

    TTriangle(const TTriangle& t);

    ~TTriangle();

    double getBase() const;

    double getHeight() const;

private:

    double Base;

    double Height;

};

//---------------------------------------------------------------------------

#endif

Once the friends have been declared, you can define them in the header file of the object as if they were part of the interface. Here is an example:

//---------------------------------------------------------------------------



#ifndef TriangleH

#define TriangleH

//---------------------------------------------------------------------------

struct TTriangle

{

    friend double Perimeter(TTriangle Tri);

    friend double Area(TTriangle Tri);



public:

    TTriangle(double B = 0.00, double H = 0.00);

    TTriangle(const TTriangle& t);

    ~TTriangle();

    double getBase() const;

    double getHeight() const;

private:

    double Base;

    double Height;

};

//---------------------------------------------------------------------------

double Perimeter(TTriangle Tri)

{

    double RootOfHB = sqrt((Tri.Base * Tri.Base) + (Tri.Height * Tri.Height));



    return Tri.Base + Tri.Height + RootOfHB;

}

//---------------------------------------------------------------------------

double Area(TTriangle Tri)

{

    return Tri.Base * Tri.Height / 2;

}

//---------------------------------------------------------------------------

#endif

Just like all the functions and methods we have used so far, friend functions also can use the convention. To fastcall friend functions, type between the return type and the function name:

//---------------------------------------------------------------------------

#ifndef TriangleH

#define TriangleH

//---------------------------------------------------------------------------

struct TTriangle

{

    friend double Perimeter(TTriangle Tri);

    friend double Area(TTriangle Tri);



public:

    TTriangle(double B = 0.00, double H = 0.00);

    TTriangle(const TTriangle& t);

    ~TTriangle();

    double getBase() const;

    double getHeight() const;

private:

    double Base;

    double Height;

};

//---------------------------------------------------------------------------

double Perimeter(TTriangle Tri)

{

    double RootOfHB = sqrt((Tri.Base * Tri.Base) + (Tri.Height * Tri.Height));



    return Tri.Base + Tri.Height + RootOfHB;

}

//---------------------------------------------------------------------------

double Area(TTriangle Tri)

{

    return Tri.Base * Tri.Height / 2;

}

//---------------------------------------------------------------------------

#endif

Since you will usually choose to hide your hard work, you can define the friend functions in the source file of the object, as follows:

//---------------------------------------------------------------------------

#include <math>

using namespace std;



#include "Triangle.h"

//---------------------------------------------------------------------------



//---------------------------------------------------------------------------

double Perimeter(TTriangle Tri)

{

    double RootOfHB = sqrt((Tri.Base * Tri.Base) + (Tri.Height * Tri.Height));



    return Tri.Base + Tri.Height + RootOfHB;

}

//---------------------------------------------------------------------------

double Area(TTriangle Tri)

{

    return Tri.Base * Tri.Height / 2;

}

//---------------------------------------------------------------------------

TTriangle::TTriangle(double B, double H)

    : Base(B), Height(H)

{

}

//---------------------------------------------------------------------------

TTriangle::TTriangle(const TTriangle& t)

    : Base(t.Base), Height(t.Height)

{

}

//---------------------------------------------------------------------------

TTriangle::~TTriangle()

{

}

//---------------------------------------------------------------------------

double TTriangle::getBase() const

{

    return Base;

}

//---------------------------------------------------------------------------

double TTriangle::getHeight() const

{

    return Height;

}

//---------------------------------------------------------------------------

Friends are called like any other regular global functions, by their names. They do not need to be qualified with the period operator. Therefore, they can be called by any function. They can be passed any variable declared from the friendly object; and as you know already, they have access to all members of the object. Here is a declaration of the TTriangle object in the main() function, We use an external function to display the characteristics of the object. Notice that this external function calls the friend functions of the class without qualifying them:

//---------------------------------------------------------------------------

#include <iostream>

#include <iomanip>

using namespace std;

#include "Triangle.h"

//---------------------------------------------------------------------------





//---------------------------------------------------------------------------

void Characteristics(const TTriangle& T)

{

    cout << "Characteristics of the triangle\n";

    cout << setiosflags(ios::fixed) << setprecision(2);

    cout << "Base:      " << T.getBase() << endl;

    cout << "Height:    " << T.getHeight() << endl;

    cout << "Perimeter: " << Perimeter(T) << endl;

    cout << "Area:      " << Area(T) << endl;

}

//---------------------------------------------------------------------------

int main(int argc, char* argv[])

{

    TTriangle Trng(12.55, 10.85);



    Characteristics(Trng);



    

    

    return 0;

}

//---------------------------------------------------------------------------

Here is an example of running the program:

Characteristics of the triangle

Base:      12.55

Height:    10.85

Perimeter: 39.99

Area:      68.08



When a friend function does not modify the value(s) of the object’s member variable(s) it accesses, like a regular function, you should pass the object as a constant to protect your variables from erroneous modification. Here is an example:

//---------------------------------------------------------------------------

#ifndef TriangleH

#define TriangleH

//---------------------------------------------------------------------------

struct TTriangle

{

    friend double Perimeter(const TTriangle Tri);

    friend double Area(const TTriangle Tri);



public:

    TTriangle(double B = 0.00, double H = 0.00);

    TTriangle(const TTriangle& t);

    ~TTriangle();

    double getBase() const;

    double getHeight() const;

private:

    double Base;

    double Height;

};

//---------------------------------------------------------------------------

#endif

Of course, remember that the const keyword is used both when declaring the function and when defining it:

//---------------------------------------------------------------------------

double Perimeter(const TTriangle Tri)

{

    double RootOfHB = sqrt((Tri.Base * Tri.Base) + (Tri.Height * Tri.Height));



    return Tri.Base + Tri.Height + RootOfHB;

}

//---------------------------------------------------------------------------

double Area(const TTriangle Tri)

{

    return Tri.Base * Tri.Height / 2;

}

//---------------------------------------------------------------------------

When the compiler is accessing an object passed by value, there is overhead involved with going back and forth from the declaration to the definition of the object. One way you can improve the speed of this execution is to pass the object to its friend(s) as reference. This will allow the (friend) function(s) to access the object directly at its location in memory. Here is an example:

//---------------------------------------------------------------------------

#ifndef TriangleH

#define TriangleH

//---------------------------------------------------------------------------

struct TTriangle

{

    friend double Perimeter(TTriangle& Tri);

    friend double Area(TTriangle& Tri);



public:

    . . .

private:

    double Base;

    double Height;

};

//---------------------------------------------------------------------------

#endif

One more technique used to accelerate code execution when a (friend) function (or any function) does not modify the member variables of the object it receives is to not only pass it as a constant, but also by reference. Using this technique, although the function has access to the address of the object, the function cannot modify the object’s variables values. Here is our new header file:

//---------------------------------------------------------------------------

#ifndef TriangleH

#define TriangleH

//---------------------------------------------------------------------------

struct TTriangle

{

    friend double Perimeter(const TTriangle& Tri);

    friend double Area(const TTriangle& Tri);



public:

    . . .

private:

    double Base;

    double Height;

};

//---------------------------------------------------------------------------

#endif

When defining the (friend) functions, remember to use the same system of passing arguments as their declarations: Any function that does not modify the object argument it receives should have the object passed as a constant reference.

As an “acquaintance” of the object, a friend function is sometimes asked to perform assignments such as building and returning the object. This is the same technique used to return a complete object. To declare such a function, type the friend keyword, followed by the name of the class, followed by the name of the function and its parentheses. Possible arguments are an option. Here is an example:

//---------------------------------------------------------------------------

#ifndef TriangleH

#define TriangleH

//---------------------------------------------------------------------------

struct TTriangle

{

    friend TTriangle GetDimensions();

    friend double Perimeter(const TTriangle& Tri);

    friend double Area(const TTriangle& Tri);



public:

    TTriangle(double B = 0.00, double H = 0.00);

    TTriangle(const TTriangle& t);

    ~TTriangle();

    void setDimensions(const double b, const double h);

    double getBase() const;

    double getHeight() const;

private:

    double Base;

    double Height;

};

//---------------------------------------------------------------------------

#endif

The function would be defined as a regular function that returns the object:

//---------------------------------------------------------------------------

TTriangle GetDimensions()

{

    double x, y;



    cout << "Enter base: "; cin >> x;

    cout << "Enter height: "; cin >> y;



    return TTriangle(x, y);

}

//---------------------------------------------------------------------------

When calling this function, you can assign its returned value to a variable declared from the friendly object. Here is how it could be done in the main() function:

//---------------------------------------------------------------------------

#include <iostream>

#include <iomanip>

using namespace std;

#include "Triangle.h"

//---------------------------------------------------------------------------





void Characteristics(const TTriangle& T)

{

    cout << "\nCharacteristics of the triangle\n";

    cout << setiosflags(ios::fixed) << setprecision(2);

    cout << "Base:      " << T.getBase() << endl;

    cout << "Height:    " << T.getHeight() << endl;

    cout << "Perimeter: " << Perimeter(T) << endl;

    cout << "Area:      " << Area(T) << endl;

}

//---------------------------------------------------------------------------

int main(int argc, char* argv[])

{

    TTriangle Slice;

    double b, h;



    Slice = GetDimensions();

    Characteristics(Slice);



    

    

    return 0;

}

//---------------------------------------------------------------------------
 

Using Friends of a Class

  1. To declare a friend function of a class, change the header file as follows:
     
    //---------------------------------------------------------------------------
    
    #ifndef StudentsH
    
    #define StudentsH
    
    #include <iostream>
    
    //---------------------------------------------------------------------------
    
    class TStudent
    
    {
    
        friend TStudent Registration();
    
    public:
    
        TStudent();
    
        TStudent(string FN, string LN);
    
        TStudent(string fn, string ln, int d, int m, int y);
    
        TStudent(const TStudent& S);
    
        ~TStudent();
    
        void setFirstName(string f) { FirstName = f; }
    
        string getFirstName() { return FirstName; }
    
        void setLastName(string l) { LastName = l; }
    
        string getLastName() { return LastName; }
    
        void setDayOfBirth(int d) { DayOfBirth = d; }
    
        int getDayOfBirth() { return DayOfBirth; }
    
        void setMonthOfBirth(int m) { MonthOfBirth = m; }
    
        int getMonthOfBirth() { return MonthOfBirth; }
    
        void setYearOfBirth(int y) { YearOfBirth = y; }
    
        int getYearOfBirth() { return YearOfBirth; }
    
    
    
    private:
    
        string FirstName;
    
        string LastName;
    
        int DayOfBirth;
    
        int MonthOfBirth;
    
        int YearOfBirth;
    
    };
    
    //---------------------------------------------------------------------------
    
    #endif
  2. Change the source file as follows:
     
    //---------------------------------------------------------------------------
    
    
    
    using namespace std;
    
    
    
    #include "Students.h"
    
    //---------------------------------------------------------------------------
    
    
    
    
    
    //---------------------------------------------------------------------------
    
    TStudent Registration()
    
    {
    
        TStudent S;
    
    
    
        // Notice that the function has access to the
    
        // private members of the class
    
        cout << "Enter the student's information\n";
    
        cout << "First Name: "; cin >> S.FirstName;
    
        cout << "Last Name: "; cin >> S.LastName;
    
        cout << "Day of Birth: "; cin >> S.DayOfBirth;
    
        cout << "Month of Birth: "; cin >> S.MonthOfBirth;
    
        cout << "Year of Birth: "; cin >> S.YearOfBirth;
    
    
    
        return S;
    
    }
    
    //---------------------------------------------------------------------------
    
    TStudent::TStudent()
    
    {
    
        FirstName = "John";
    
        LastName = "Doe";
    
        DayOfBirth = 1;
    
        MonthOfBirth = 1;
    
        YearOfBirth = 1990;
    
    }
    
    //---------------------------------------------------------------------------
    
    TStudent::TStudent(string FN, string LN)
    
        : FirstName(FN), LastName(LN),
    
          DayOfBirth(1), MonthOfBirth(1), YearOfBirth(1990)
    
    {
    
        
    
    }
    
    //---------------------------------------------------------------------------
    
    TStudent::TStudent(string fn, string ln, int d, int m, int y)
    
        : FirstName(fn), LastName(ln),
    
          DayOfBirth(d), MonthOfBirth(m), YearOfBirth(y)
    
    {
    
        
    
    }
    
    //---------------------------------------------------------------------------
    
    TStudent::TStudent(const TStudent& Stud)
    
        : FirstName(Stud.FirstName),
    
          LastName(Stud.LastName),
    
          DayOfBirth(Stud.DayOfBirth),
    
          MonthOfBirth(Stud.MonthOfBirth),
    
          YearOfBirth(Stud.YearOfBirth)
    
    {
    
    }
    
    //---------------------------------------------------------------------------
    
    TStudent::~TStudent()
    
    {
    
        //TODO: Add your source code here
    
    }
    
    //---------------------------------------------------------------------------
  3. Change the Main.cpp file as follows:
     
    //---------------------------------------------------------------------------
    
    #include <iostream>
    
    using namespace std;
    
    #include "Students.h"
    
    //---------------------------------------------------------------------------
    
    int main(int argc, char* argv[])
    
    {
    
        TStudent Stud;
    
        void StudentInfo(TStudent Grade1);
    
    
    
        Stud = Registration();
    
        StudentInfo(Stud);
    
    
    
        
    
        
    
        return 0;
    
    }
    
    //---------------------------------------------------------------------------
    
    void StudentInfo(TStudent s)
    
    {
    
        cout << "\nStudent Registration";
    
        cout << "\nFull Name: "
    
             << s.getFirstName() << " " << s.getLastName();
    
        cout << "\nDate of Birth: " << s.getDayOfBirth() << "/"
    
             << s.getMonthOfBirth() << "/" << s.getYearOfBirth();
    
    }
    
    //---------------------------------------------------------------------------
  4. Test the program. Here is an example:
     
    Enter the student's information
    
    First Name: Josh
    
    Last Name: Annett
    
    Day of Birth: 10
    
    Month of Birth: 12
    
    Year of Birth: 1985
    
    
    
    Student Registration
    
    Full Name: Josh Annett
    
    Date of Birth: 10/12/1985
  5. Return to your programming environment
  6. To pass a class to a friend as a reference, change the declaration of the friend function in the header file as follows:
     
    //---------------------------------------------------------------------------
    
    #ifndef StudentsH
    
    #define StudentsH
    
    #include <iostream>
    
    //---------------------------------------------------------------------------
    
    class TStudent
    
    {
    
        friend void Registration(TStudents &Student);
    
    
    
    public:
    
        . . .
    
    
    
    private:
    
        . . .
    
    };
    
    //---------------------------------------------------------------------------
    
    #endif
  7. Change the implementation of the friend function as follows:
     
    //---------------------------------------------------------------------------
    
    void Registration(TStudents &S)
    
    {
    
        // Notice that the function has access to the
    
        // private members of the class
    
        cout << "Enter the student's information\n";
    
        cout << "First Name: "; cin >> S.FirstName;
    
        cout << "Last Name: "; cin >> S.LastName;
    
        cout << "Day of Birth: "; cin >> S.DayOfBirth;
    
        cout << "Month of Birth: "; cin >> S.MonthOfBirth;
    
        cout << "Year of Birth: "; cin >> S.YearOfBirth;
    
    }
    
    //---------------------------------------------------------------------------
  8. Test the program and return to your programming environment

Mixing Different Objects in the Same Program

Before using different objects in your program, they must be known to the compiler. These objects could be part of the operating system, they could be part of C++ Builder, they could be defined as C++ objects, or you can create your own. To start, we will learn how to use objects that we create.

An office supplies store has hired you to write a program that will allow customers to create their own business labels using a computer located somewhere in the store. We will use two objects for our program. TDimensions will define the dimensions of the label and another object called TLabelType will define the paper quality.

A classic label has dimensions set by a length and a width. When a user or another part of the program calls the label, it mostly uses constructors; and we will use them. The first constructor takes no argument; it is used to set the default dimensions for the label. The second constructor will make sure that the supplied dimensions, if any, are correct. To protect our dimensions, the length and the width will be private; we will provide access methods to get the dimensions:

//---------------------------------------------------------------------------

#ifndef RectangleH

#define RectangleH

//---------------------------------------------------------------------------

class TRectangle

{

public:

    TRectangle();

    TRectangle(double L, double W);

    TRectangle(const TRectangle& Rect);

    ~TRectangle();

    void setLength(double L) { Length = L; }

    void setHeight(double H) { Height = H; }

    double getLength() { return Length; }

    double getHeight() { return Height; }

    double Perimeter(double Length, double Height);

    double Area(double Length, double Height);

private:

    double Length;

    double Height;

};

//---------------------------------------------------------------------------

#endif

The source file initializes the object, controls the dimensions, and calculates the area:

//---------------------------------------------------------------------------



using namespace std;



#include "Rectangle.h"

//---------------------------------------------------------------------------



TRectangle::TRectangle()

    : Length(3.25), Height(2.55)

{

    //TODO: Add your source code here

}

//---------------------------------------------------------------------------

TRectangle::TRectangle(double L, double H)

    : Length(L), Height(H)

{

    //TODO: Add your source code here

}

//---------------------------------------------------------------------------

TRectangle::TRectangle(const TRectangle& r)

    : Length(r.Length), Height(r.Height)

{

    //TODO: Add your source code here

}

//---------------------------------------------------------------------------

TRectangle::~TRectangle()

{

    //TODO: Add your source code here

}

//---------------------------------------------------------------------------

double TRectangle::Perimeter(double x, double y)

{

    return 2 * (x + y);

}

//---------------------------------------------------------------------------

double TRectangle::Area(double x, double y)

{

    return x * y;

}

//---------------------------------------------------------------------------

The second object specifies the characteristics of the label including its model number, its color, whether the label will use a removable or a non-removable adhesive. Once again, we will use two constructors for the same reasons as above.

Header File: LabelType.h

//---------------------------------------------------------------------------

#ifndef LabelTypeH

#define LabelTypeH

#include <string>

using namespace std;

//---------------------------------------------------------------------------

class TLabelType

{

public:

    TLabelType();

    TLabelType(long m, string c, string n, string a);

    ~TLabelType();

    void setModelNumber(long m) { ModelNumber = m; }

    void setName(string n) { Name = n; }

    void setColor(string c) { Color = c; }

    void setAdhesive(string a) { Adhesive = a; }

    long getModelNumber() const;

    string getName() const;

    string getColor() const;

    string getAdhesive() const;

private:

    long ModelNumber;

    string Name;

    string Color;

    string Adhesive;

};

//---------------------------------------------------------------------------

#endif

The implementation file of the TLabelType object is used to initialize an object and control its properties.

Source File: LabelType.cpp

//---------------------------------------------------------------------------



using namespace std;



#include "LabelType.h"

//---------------------------------------------------------------------------



TLabelType::TLabelType()

    : ModelNumber(0), Color("White"),

      Name("None"), Adhesive("Not Specified")

{

    //TODO: Add your source code here

}

//---------------------------------------------------------------------------

TLabelType::TLabelType(long m, string c, string n, string a)

    : ModelNumber(m), Color(c), Name(n), Adhesive(a)

{

    //TODO: Add your source code here

}

//---------------------------------------------------------------------------

TLabelType::~TLabelType()

{

    //TODO: Add your source code here

}

//---------------------------------------------------------------------------

long TLabelType::getModelNumber() const

{

    return ModelNumber;

}

//---------------------------------------------------------------------------

string TLabelType::getName() const

{

    return Name;

}

//---------------------------------------------------------------------------

string TLabelType::getColor() const

{

    return Color;

}

//---------------------------------------------------------------------------

string TLabelType::getAdhesive() const

{

    return Adhesive;

}

//---------------------------------------------------------------------------

Once you have objects, you can declare each when desired and supply its properties if needed. In our main() function, we will first call the TDimension and the TLabelType objects using empty contructors. Whenever any function or object calls an object without specifying the properties, each object will display its default values:

Main File: Main.cpp

//---------------------------------------------------------------------------

#include <iostream>

#include <iomanip>

using namespace std;

#include "Rectangle.h"

#include "LabelType.h"

//---------------------------------------------------------------------------

int main(int argc, char* argv[])

{

    TRectangle Dim;

    TLabelType LabelType;



    cout << "A label with default characteristics";

    cout << "\nDimensions: " << Dim.getLength()

         << " * " << Dim.getHeight();

    cout << "\nArea:       " << Dim.Area(Dim.getLength(), Dim.getHeight());

    cout << "\nModel No.:  " << LabelType.getModelNumber();

    cout << "\nModel Name: " << LabelType.getName();

    cout << "\nColor:      " << LabelType.getColor();

    cout << "\nAdhesive:   " << LabelType.getAdhesive();



    

    

    return 0;

}

//---------------------------------------------------------------------------

The program would produce:

A label with default characteristics

Dimensions: 3.25 * 2.55

Area:       8.2875

Model No.:  0

Model Name: None

Color:      White

Adhesive:   Not Specified



The program can also provide the values of each object, using their methods:

Main File: Main.cpp

//---------------------------------------------------------------------------

#include <iostream>

#include <iomanip>

using namespace std;

#include "Rectangle.h"

#include "LabelType.h"

//---------------------------------------------------------------------------





//---------------------------------------------------------------------------

int main(int argc, char* argv[])

{

    TRectangle Dim(4.55, 2.25);

    TLabelType LabelType(25442, "Mandarin", "One Touch", "Non-Removable");



    cout << "An example label";

    cout << "\nDimensions: " << Dim.getLength()

         << " * " << Dim.getHeight();

    cout << "\nArea:       " << Dim.Area(Dim.getLength(), Dim.getHeight());

    cout << "\nModel No.:  " << LabelType.getModelNumber();

    cout << "\nModel Name: " << LabelType.getName();

    cout << "\nColor:      " << LabelType.getColor();

    cout << "\nAdhesive:   " << LabelType.getAdhesive();



    

    

    return 0;

}

//---------------------------------------------------------------------------

This time, the program would display different values:

An example label

Dimensions: 4.55 * 2.25

Area:       10.2375

Model No.:  25442

Model Name: One Touch

Color:      Mandarin

Adhesive:   Non-Removable



 

Combining Objects

  1. To process a semi-complete registration for a student, consisting of a complete address, change the Students.h file as follows:
     
    //---------------------------------------------------------------------------
    
    #ifndef StudentsH
    
    #define StudentsH
    
    #include <iostream>
    
    //---------------------------------------------------------------------------
    
    class TStudent
    
    {
    
        friend void Registration(TStudent &Student);
    
    
    
    public:
    
        TStudent();
    
        TStudent(string FN, string LN);
    
        TStudent(string fn, string ln, int d, int m, int y);
    
        TStudent(const TStudent& S);
    
        ~TStudent();
    
        void setFirstName(string f) { FirstName = f; }
    
        string getFirstName() const { return FirstName; }
    
        void setLastName(string l) { LastName = l; }
    
        string getLastName() const { return LastName; }
    
        void setDayOfBirth(int d) { DayOfBirth = d; }
    
        int getDayOfBirth() const { return DayOfBirth; }
    
        void setMonthOfBirth(int m) { MonthOfBirth = m; }
    
        int getMonthOfBirth() const { return MonthOfBirth; }
    
        void setYearOfBirth(int y) { YearOfBirth = y; }
    
        int getYearOfBirth() const { return YearOfBirth; }
    
        void setAddress(string a) { Address = a; }
    
        string getAddress() const { return Address; }
    
        void setCity(string c) { City = c; }
    
        string getCity() const { return City; }
    
        void setState(string s) { State = s; }
    
        string getState() const { return State; }
    
        void setZIPCode(string z) { ZIPCode = z; }
    
        string getZIPCode() const { return ZIPCode; }
    
        void setCountry(string c) { Country = c; }
    
        string getCountry() const { return Country; }
    
    
    
    private:
    
        string FirstName;
    
        string LastName;
    
        int DayOfBirth;
    
        int MonthOfBirth;
    
        int YearOfBirth;
    
        string Address;
    
        string City;
    
        string State;
    
        string ZIPCode;
    
        string Country;
    
    };
    
    //---------------------------------------------------------------------------
    
    #endif
  2. Change the Students.cpp file as follows:
     
    //---------------------------------------------------------------------------
    
    
    
    using namespace std;
    
    
    
    #include "Students.h"
    
    //---------------------------------------------------------------------------
    
    
    
    
    
    //---------------------------------------------------------------------------
    
    void Registration(TStudent &S)
    
    {
    
        // Notice that the function has access to the
    
        // private members of the class
    
        cout << "Enter the student's information\n";
    
        cout << "First Name:     "; cin >> S.FirstName;
    
        cout << "Last Name:      "; cin >> S.LastName;
    
        cout << "Day of Birth:   "; cin >> S.DayOfBirth;
    
        cout << "Month of Birth: "; cin >> S.MonthOfBirth;
    
        cout << "Year of Birth:  "; cin >> S.YearOfBirth;
    
        cout << "Address: ";
    
        cin >> ws;
    
        getline(cin, S.Address);
    
        cout << "City:    ";
    
        getline(cin, S.City);
    
        cout << "State:   ";
    
        getline(cin, S.State);
    
        cout << "ZIPCode: ";
    
        getline(cin, S.ZIPCode);
    
        cout << "Country: ";
    
        getline(cin, S.Country);
    
    }
    
    //---------------------------------------------------------------------------
    
    TStudent::TStudent()
    
    {
    
        FirstName    = "John";
    
        LastName     = "Doe";
    
        DayOfBirth   = 1;
    
        MonthOfBirth = 1;
    
        YearOfBirth  = 1990;
    
        Address      = "123 Main Street";
    
        City         = "Old Town";
    
        State        = "This State";
    
        ZIPCode      = "01234-0001";
    
        Country      = "USA";
    
    }
    
    //---------------------------------------------------------------------------
    
    TStudent::TStudent(string FN, string LN)
    
        : FirstName(FN), LastName(LN),
    
          DayOfBirth(1), MonthOfBirth(1), YearOfBirth(1990),
    
          Address("123 Main Street"),
    
          City("This State"),
    
          State("Unkown"),
    
          ZIPCode("00001-0001"),
    
          Country("USA")
    
    {
    
        
    
    }
    
    //---------------------------------------------------------------------------
    
    TStudent::TStudent(string fn, string ln, int d, int m, int y)
    
        : FirstName(fn), LastName(ln),
    
          DayOfBirth(d), MonthOfBirth(m), YearOfBirth(y),
    
          Address("123 Main Street"),
    
          City("This State"),
    
          State("Unkown"),
    
          ZIPCode("00001-0001"),
    
          Country("USA")
    
    {
    
        
    
    }
    
    //---------------------------------------------------------------------------
    
    TStudent::TStudent(const TStudent& Stud)
    
        : FirstName(Stud.FirstName),
    
          LastName(Stud.LastName),
    
          DayOfBirth(Stud.DayOfBirth),
    
          MonthOfBirth(Stud.MonthOfBirth),
    
          YearOfBirth(Stud.YearOfBirth),
    
          Address(Stud.Address),
    
          City(Stud.City),
    
          State(Stud.State),
    
          ZIPCode(Stud.ZIPCode),
    
          Country(Stud.Country)
    
    {
    
    }
    
    //---------------------------------------------------------------------------
    
    TStudent::~TStudent()
    
    {
    
        //TODO: Add your source code here
    
    }
    
    //---------------------------------------------------------------------------
  3. Create a new 
  4. class called TGrades object and change the Grades.h file as follows:
     
    //---------------------------------------------------------------------------
    
    
    
    #ifndef GradesH
    
    #define GradesH
    
    //---------------------------------------------------------------------------
    
    #endif
    
    //---------------------------------------------------------------------------
    
    class TGrades
    
    {
    
        friend void GetGrades(TGrades&);
    
    public:
    
        TGrades();
    
        TGrades(double e, double s, double h,
    
                           double g, double c, double o,
    
                           double m, double p, double r, double t);
    
        ~TGrades();
    
        void setEnglish(double e) { English = e; }
    
        double getEnglish() { return English; }
    
        void setSecondLng(double s) { SecondLng = s; }
    
        double getSecondLng() { return SecondLng; }
    
        void setHistory(double h) { History = h; }
    
        double getHistory() { return History; }
    
        void setGeography(double g) { Geography = g; }
    
        double getGeography() { return Geography; }
    
        void setChemistry(double c) { Chemistry = c; }
    
        double getChemistry() { return Chemistry; }
    
        void setSociology(double o) { Sociology = o; }
    
        double getSociology() { return Sociology; }
    
        void setMath(double m) { Math = m; }
    
        double getMath() { return Math; }
    
        void setCompSc(double p) { CompSc = p; }
    
        double getCompSc() { return CompSc; }
    
        void setMorale(double a) { Morale = a; }
    
        double getMorale() { return Morale; }
    
        void setSports(double t) { Sports = t; }
    
        double getSports() { return Sports; }
    
        double CalcTotal();
    
        double CalcMean();
    
    private:
    
        double English;
    
        double SecondLng;
    
        double History;
    
        double Geography;
    
        double Chemistry;
    
        double Sociology;
    
        double Math;
    
        double CompSc;
    
        double Morale;
    
        double Sports;
    
    };
  5. To implement the TGrades object, change the Grades.cpp file as follows:
     
    //---------------------------------------------------------------------------
    
    #include <iostream>
    
    using namespace std;
    
    
    
    #include "Grades.h"
    
    //---------------------------------------------------------------------------
    
    
    
    TGrades::TGrades()
    
        : English(0.00),
    
          SecondLng(0.00),
    
          History(0.00),
    
          Geography(0.00),
    
          Chemistry(0.00),
    
          Sociology(0.00),
    
          Math(0.00),
    
          CompSc(0.00),
    
          Morale(0.00),
    
          Sports(0.00)
    
    {
    
    }
    
    //---------------------------------------------------------------------------
    
    TGrades::TGrades(double e, double s, double h,
    
                                double g, double c, double o,
    
                                double m, double p, double r, double t)
    
        : English(e),
    
          SecondLng(s),
    
          History(h),
    
          Geography(g),
    
          Chemistry(c),
    
          Sociology(o),
    
          Math(m),
    
          CompSc(p),
    
          Morale(r),
    
          Sports(t)
    
    {
    
    }
    
    //---------------------------------------------------------------------------
    
    TGrades::~TGrades()
    
    {
    
        //TODO: Add your source code here
    
    }
    
    //---------------------------------------------------------------------------
    
    double TGrades::CalcTotal()
    
    {
    
        double Total = English + SecondLng + History +
    
                       Geography + Chemistry + Sociology +
    
                       Math + CompSc + Morale + Sports;
    
    
    
        return Total;
    
    }
    
    //---------------------------------------------------------------------------
    
    double TGrades::CalcMean()
    
    {
    
        return CalcTotal() / 10;
    
    }
    
    //---------------------------------------------------------------------------
    
    void GetGrades(TGrades& Student)
    
    {
    
        cout << "English:         "; cin >> Student.English;
    
        cout << "Second Language: "; cin >> Student.SecondLng;
    
        cout << "History:         "; cin >> Student.History;
    
        cout << "Geography:       "; cin >> Student.Geography;
    
        cout << "Chemistry:       "; cin >> Student.Chemistry;
    
        cout << "Sociology:       "; cin >> Student.Sociology;
    
        cout << "Mathematics:     "; cin >> Student.Math;
    
        cout << "Comp Sciences:   "; cin >> Student.CompSc;
    
        cout << "Morale:          "; cin >> Student.Morale;
    
        cout << "Sports:          "; cin >> Student.Sports;
    
    }
    
    //---------------------------------------------------------------------------
  6. To use both objects in the same program, implement the Main.cpp file as follows:
     
    //---------------------------------------------------------------------------
    
    #include <iostream>
    
    #include <iomanip>
    
    using namespace std;
    
    #include "Students.h"
    
    #include "Grades.h"
    
    //---------------------------------------------------------------------------
    
    int main(int argc, char* argv[])
    
    {
    
        TStudent Stud;
    
        TGrades Grade;
    
        void StudentInfo(TStudent Grade1);
    
        void ShowGrades(TGrades d);
    
    
    
        cout << "Student Registration\n";
    
        Registration(Stud);
    
        cout << endl;
    
        cout << "Student Grades\n";
    
        GetGrades(Grade);
    
    
    
        system("cls");
    
    
    
        StudentInfo(Stud);
    
        ShowGrades(Grade);
    
    
    
        
    
        
    
        return 0;
    
    }
    
    //---------------------------------------------------------------------------
    
    void StudentInfo(TStudent s)
    
    {
    
        cout << "====================================";
    
        cout << "\nStudent Report";
    
        cout << "\n------------------------------------";
    
        cout << "\nStudent Registration";
    
        cout << "\nFull Name: "
    
             << s.getFirstName() << " " << s.getLastName();
    
        cout << "\nDate of Birth: " << s.getDayOfBirth() << "/"
    
             << s.getMonthOfBirth() << "/" << s.getYearOfBirth();
    
        cout << "\nAddress:   " << s.getAddress()
    
             << "\n           " << s.getCity() << ", " << s.getState()
    
             << ", " << s.getZIPCode()
    
             << "\n           " << s.getCountry();
    
    }
    
    //---------------------------------------------------------------------------
    
    void ShowGrades(TGrades d)
    
    {
    
        cout << setiosflags(ios::fixed) << setprecision(2);
    
        cout << "\n------------------------------------";
    
        cout << "\n\tEnglish:       " << d.getEnglish();
    
        cout << "\n\tLanguage 2:    " << d.getSecondLng();
    
        cout << "\n\tHistory:       " << d.getHistory();
    
        cout << "\n\tGeography:     " << d.getGeography();
    
        cout << "\n\tChemistry:     " << d.getChemistry();
    
        cout << "\n\tSociology:     " << d.getSociology();
    
        cout << "\n\tMathematics:   " << d.getMath();
    
        cout << "\n\tComp Sciences: " << d.getCompSc();
    
        cout << "\n\tMorale:        " << d.getMorale();
    
        cout << "\n\tSports:        " << d.getSports();
    
        cout << "\n------------------------------------";
    
        cout << "\n\tTotal: " << d.CalcTotal() << "\tMean: " << d.CalcMean();
    
        cout << "\n====================================";
    
    }
    
    //---------------------------------------------------------------------------
  7. To test the program, press F9. Here is an example:
     
    First Screen:
     
    Student Registration
    
    Enter the student's information
    
    First Name:     Paul
    
    Last Name:      Delamarre
    
    Day of Birth:   28
    
    Month of Birth: 2
    
    Year of Birth:  1986
    
    Address: 8402 Norton Hwy #D12
    
    City:    Silver Spring
    
    State:   MD
    
    ZIPCode: 20910-4412
    
    Country: USA
    
    
    
    Student Grades
    
    English:         12.50
    
    Second Language: 10.25
    
    History:         14.50
    
    Geography:       13.00
    
    Chemistry:       15.00
    
    Sociology:       12.50
    
    Mathematics:     16.50
    
    Comp Sciences:   17.25
    
    Morale:          14.00
    
    Sports:          15.50

    Second Screen:
     
    ====================================
    
    Student Report
    
    ------------------------------------
    
    Student Registration
    
    Full Name: Paul Delamarre
    
    Date of Birth: 28/2/1986
    
    Address:   8402 Norton Hwy #D12
    
               Silver Spring, MD, 20910-4412
    
               USA
    
    ------------------------------------
    
            English:       12.50
    
            Language 2:    10.25
    
            History:       14.50
    
            Geography:     13.00
    
            Chemistry:     15.00
    
            Sociology:     12.50
    
            Mathematics:   16.50
    
            Comp Sciences: 17.25
    
            Morale:        14.00
    
            Sports:        15.50
    
    ------------------------------------
    
            Total: 141.00   Mean: 14.10
    
    ====================================

  8. Return to your programming environment

 

 
 

Previous Copyright © 2000-2005 FunctionX, Inc. Next