Object’s in C++

C++ Object

When a class is defined, only the specification for the object is defined, no memory or storage is allocated. To use the data and access functions defined in the class, you need to create objects. An object’s in c++ is known as instance of class.  

Syntax for declaring object’s in c++ :

class_name object name;

Accessing member : to access the members of class the dot operator is used.

Example :

s.get();
s.put();

Program 1.1:

# include<iostream>
using namespace std;
class sample
{
private :
int r;
char ch[20];

public:
void get_data()
{
cout<<”Enter roll number”;
cin>>r;
cout<<”Enter name”;
cin>>ch;
}

void put_data()
{
cout<<”roll number is:”<<r;
cout<<”Name is:”<<ch;
}
int main()
{
sample s;
s.get_data();
s.put_data();
return 0;
}

Scope Resolution operator:

Scope:-Visibility or availability of a variable in a program is called as scope. There are two types of scope.
i)Local scope
ii)Global scope

Local scope: visibility of a variable is local to the function in which it is declared.

Global scope: visibility of a variable to all functions of a program.

Scope resolution operator in “::” . This is used to access global variables if same variables are declared as local and global.

Program 1.2:

# include<iostream.h>
using namespace std;
a = 10;
int main()
{
int a=1;
cout<<”Local value is:”<<a<<endl;
cout<<”Global value is:”<<::a;
return 0;
}

Output :
Local value is:1
Global value is:10


1 thought on “Object’s in C++”