Introduction to Classes and Objects| OOP in C++


Limitation of Structures


The standard C does not allow the struct data type to be treated as built-in type.
For example:


Struct mynum
{
float a;
float b;
};


Struct mynum m1, m2, m3;
But m3=m1+m2; is illegal in C.
Another limitation of C structures is that they do not permit data hiding, structure members are public and can be accessed by any function within the scope.

C++ defines a new user defined data type is called Class. A class supports all object oriented programming concept like inheritance.etc.

In C++, the only difference between class and a structure is by default the members of a class are private and by default members of structure are public.

A class is an abstract data type and can be treated as any built-in data type. A class contains data members and member functions which are meant to operate on data members.
Example:


Class class_name
{
private:
variable declarations;
function declarations;
};


Here, keywords private and public are known as visibility labels.
Points:

1. Usage of keyword private is optional by default, all the members are private.
2. Only member functions can have access to the private data members and private functions. However, public members can be accessed from outside the class using objects of the same class.
3. A variable of a class is called object. Every class has it's object. Object gets memory.
4. A member function can be defined in two places

a. Outside class definition
b. Inside class definition


Program to add two numbers using class:


#include<iostream.h>
Class myadd
{
float a, b, result;
Public:
Void getdata(float x, float y);
Void addnum(void);
Void display(void){
cout<<"\nAddition="<<result;
}
};
Void myadd::getdata(float x, float y)
{
a=x;
b=y;
}
void myadd::addnum(void)
{
result=a+b;
}
int main()
{
myadd z1;
z1.getdata(100.25, 75.50);
z1.addnum();
z1.display();
myadd z2;
z2.getdata(75.5, 500.70);
z2.addnum();
z2.display();
return 0;
}


Nesting of member function


A member function can be called within another member function of the same class without using object.

#include<iostream.h>
class largestnum
{
int a, b;
public:
void getnum(int x, int y);
int mylargest(void);
void display(void);
};
void largestnum::getnum(int x, int y)
{
a=x;
b=y;
}
int largestnum::mylargest(void)
{
if(a>=b)
return a;
}
void largest::display(void)
{
cout<<"Largest"<<mylargest();
}
int main()
{
largestnum t;
t.getnum(7,15);
t.display();
return 0;
}

Note:- Private member functions cannot be accessed my the object, they can only be called by other member functions of the same class.

Custom Search

%d bloggers like this: