The C++ nested class object, accessing and using method in other class C++ code 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: Demonstrating the C++ nested class object in C++ programming

To show: How to create and use the C++ nested class object, accessing and using method in other class in C++ programming




// the C++ nested class object, object in object

#include <iostream>

using namespace std;


// first class declaration

class mail_info


// private by default

int shipper;

int postage;



void set(int input_class,int input_postage)


shipper = input_class;

postage = input_postage;



int get_postage(void){return postage;}



// second class declaration

class box


int length;

int width;

mail_info label;



void set(int l,int w, int ship,int post)


length = l;

width = w;

// accessing the first class, mail_info set() method

label.set(ship, post);


int get_area(void) {return (length * width);}



// main program

void main(void)


// instantiate objects of type box

box small, medium, large;


// provide the constructor values





// print the values

cout<<"Area of small box\'s label is "<<small.get_area()<<endl<<endl;

cout<<"Area of medium box\'s label is "<<medium.get_area()<<endl<<endl;

cout<<"Area of large box\'s label is "<<large.get_area()<<endl<<endl;




Output example:


Area of small box's label is 8

Area of medium box's label is 30

Area of large box's label is 80

Press any key to continue . . .



C and C++ Programming Resources | C & C++ Code Example Index