Changing struct to class, an object construction and the normal variable 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: Changing struct to class type, object construction and instantiation with normal variable comparison in C++ programming

To show: How to change the C++ struct construct to the class type in C++ programming to demonstrate the benefits

 

// C++ program that using class instead of struct

#include <iostream>

using namespace std;

 

// class definition

class item

{

// private by default, it is public in struct, can explicitly use the private: keyword

int keep_data;

// accessible by public, this is the interface

public:

void set(int enter_value);

int get_value(void);

};

 

// class implementation

void item::set(int enter_value)

{

keep_data = enter_value;

}

 

int item::get_value(void)

{

return keep_data;

}

 

// main()

void main()

{

// three objects instantiated

item John_cat, Joe_cat, Big_cat;

 

// normal variable

int garfield;

 

// assigning values

John_cat.set(10);

Joe_cat.set(11);

Big_cat.set(12);

garfield = 13;

 

// the following are illegal cause keep_data is private by default only can be accessed through the method/interface

//

// John_cat.keep_data = 100;

// Joe_cat.keep_data = 110;

//

cout<<"Accessing data using class"<<endl;

cout<<"--------------------------"<<endl;

cout<<"Data value for John_cat is "<<John_cat.get_value()<<endl;

cout<<"Data value for Joe_cat is "<<Joe_cat.get_value()<<endl;

cout<<"Data value for Big_cat is "<<Big_cat.get_value()<<endl<<endl;

cout<<"Accessing data normally"<<endl;

cout<<"-----------------------"<<endl;

cout<<"Data value for garfield is "<<garfield<<endl;

 

return;

}

 

Output example:

 

Accessing data using class

--------------------------

Data value for John_cat is 10

Data value for Joe_cat is 11

Data value for Big_cat is 12

Accessing data normally

-----------------------

Data value for garfield is 13

Press any key to continue . . .

 

 

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