top of page
Search
Writer's pictureHarshit Sharma

Classes in C++

Class:

A class is a way to describe an entity and associated functions with it. In C++ class makes data type that is used to create objects of the type.

For example : If we need to say define a class Account we can have in that class account no, type of account and deposit and withdrawal functions.

class Account

{

int accno;

char type;

float deposit(float amount)

{

balance+=amount;

}

float withdraw(float amount)

{

balance-=amount;

}

};

Declaration of class:

From the example we see that we have defined some data members and member functions in the class and started the class with the class keyword.

So the class declaration basically include::

1.Data Member are the member of the class which define the characteristics of class.

2.Member functions are the set of operations that can be applied to objects of that class..

3.Program access level that control the access to member from within the program .The access level are private,public and protected.

4.Class Tagname that serves as a type specifier to the class using which object of class can be defined.

Syntax:

class classname

{

private:

Variable declarations;

Function declarations;

protected:

Variable declarations;

Function declarations;

public:

Variable declarations;

Function declarations;

};

Scope of class and its members:

1.Public: When members are define public then can be accessed by any function.

For example:

class x{

public:

int a;

int sqr(int a)

{

return a*a;

}

};

int main()

{

X ob 1;

int b;

Ob1.a=10;

b=ob1.sqr(5);

}

2.Protected: When members are define public then cannot e accessed by non member function similar to the private but can be accessed with the friend function.

3.Private: When members are define public then can be accessed within the class only.

For example:

class x{

int a;

int sqr(int a)

{

return a*a;

}

};

int main()

{

X ob 1;

int b;

Ob1.a=10; //cannot be accessed

b=ob1.sqr(5); //cannot be called

}

Referencing class members: A class specification does not define any objects of the class but just it defines the properties of the class. To make use of specified variables of class type to be defined.

For Example: From the above example we with the class name can declare the objects like

Account a1,a2;

class name object list(comma separated);

EXAMPLE:

class item

{

public:

int itemno;

float price;

void getdata(int I,float j)

{

item no=I;

price=j;

}

void putdata(void)

{

cout<<”Items”<<itemno;

cout<<”Price”<<price;

}

};

item s1,s2;

int main()

{

S1.getdata(1000,17.5);

}

1 view0 comments

Recent Posts

See All

Comments


Post: Blog2_Post
bottom of page