Monday 30 March 2009

Example to show the difference between struct and class in C++

This is a very simple example showing the difference between struct and class in C++. In reality there is hardly any difference between struct and class in C++. They are exactly the same except that the default is public in struct and private in class. You can do everything you can do in a class in a struct but its not a good practice. The reason being struct's are inherited from C programming and as the name suggests it was meant to represent a structure. You can also read the C++ FAQ that explains it better.


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//This very simple example demonstrates the basic difference
//between struct and class in C++

#include<iostream>

using namespace
std;

class
A {
int
a; //default in class is private

public
:
int
b;
void
initVariables(int c1, int c2, int c3)
{

a=c1, b=c2, c=c3;
}

void
printVariables()
{

cout<<"a = "<<a<<" b = "<<b<<" c = "<<c<<endl;
}


private
:
int
c;
};


struct
B {
int
a; //default in struct is public

public
:
int
b;
void
initVariables(int s1, int s2, int s3)
{

a=s1, b=s2, c=s3;
}

void
printVariables()
{

cout<<"a = "<<a<<" b = "<<b<<" c = "<<c<<endl;
}


private
:
int
c;
};


int
main()
{

A var1;
var1.initVariables(10, 11, 12);
//var1.a = 15; //Cant be changed as its private
var1.b = 16;
//var1.c = 17; //Cant be changed as its private
cout<<"Printing the variables from the class"<<endl;
var1.printVariables();

B var2;
var2.initVariables(20, 21, 22);
var2.a = 25; //possible
var2.b = 26;
//var2.c = 27; //Cant be changed as its private
cout<<"\n\nPrinting the variables from the struct"<<endl;
var2.printVariables();
cout<<"\n\n";

return
0;
}



The output is as follows:

No comments:

Post a Comment