Class in C++

Using class in C++?

Explanation

A Class is a way to bind the data and its associated functions together. All the elements of a class are private by default, even elements can be declared as public or protected. An object is an instance of a class.

Syntax:


class class-name{
access:specifier
private data and functions
}

In the above syntax the every class has a unique name, the "access:specifier" can either private, public, protected. The "protected" is used when inhertinace is applied.

Example :



#include <iostream.h>
class dat
{
private:
int sdata;
public:
void setdat( int a)
{ sdata =a; }
void show( )
{ cout << "\nSet data is " << sdata;}
};
void main()
{
dat x,y;
x.setdat(1000);
y.setdat(1245);
x.show();
y.show();
}

Result :

Set Data is:1000
Set Data is:1245

In the above class example the "private" object "sdata" is used only within the function. But the functions "setdat", "show" are used in the main function since they are "public".

C++ Tutorial


Ask Questions

Ask Question