The C++ class, object, pointer, overloading and string C++ program example
Compiler: Visual C++ Express Edition 2005
Compiled on Platform: Windows XP Pro SP2
Header file: Standard
Additional library: none/default
Additional project setting: Set project to be compiled as C++
Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)
Other info: none
To do: Embedding a string to the class object type using pointer in C++ programming
To show: How to assign a string to the class object type using pointer in C++ programming
// C++ class, object, pointer and string
#include <iostream>
using namespace std;
// class declaration
class wall
{
// private by default
int length;
int width;
// a pointer variable
char *line_of_text;
public:
// constructor declaration
wall(char *input_line);
void set(int new_length,int new_width);
int get_area(void);
// destructor
~wall();
};
// class implementation
// constructor, provide some initialization
wall::wall(char *input_line)
{
cout<<" Constructor..."<<endl;
length = 8;
width = 8;
line_of_text = input_line;
}
// this method will set a wall size to the two input parameters
void wall::set(int new_length, int new_width)
{
length = new_length;
width = new_width;
}
// this method will calculate and return the area of the wall instance
int wall::get_area(void)
{
cout<<line_of_text<<"= ";
return (length * width);
}
// destructor
wall::~wall()
{
cout<<" Destructor..."<<endl;
}
// the main program
void main(void)
{
// objects are instantiated with a string constant as the parameters
wall small("of small size "), medium("of medium size "), large("of large size ");
// overriding the default/constructor values
small.set(5, 7);
large.set(15, 20);
cout<<" Embedded string used as an object"<<endl;
cout<<" ----------------------------------"<<endl<<endl;
cout<<"Area of wall surface ";
cout<<small.get_area()<<endl;
cout<<"Area of wall surface ";
cout<<medium.get_area()<<endl;
// use default value of constructor
cout<<"Area of wall surface ";
cout<<large.get_area()<<endl;
return;
}
Output example:
Constructor...
Constructor...
Constructor...
Embedded string used as an object
----------------------------------
Area of wall surface of small size = 35
Area of wall surface of medium size = 64
Area of wall surface of large size = 300
Destructor...
Destructor...
Destructor...
Press any key to continue . . .