Accessing class members, Memory allocation for objects Explain With Program and Examples
Accessing class members:-
To access members of a class using the member off operator dot ( . )
It is not possible to access private data members of a class out side the class definition using dot operator
The member access operator is not required to access data members within the class definition.
Syntax for accessing members of a class:
Access data members: object_name.datamember;
For Pointer Objects : Pointer-Object-Name -> member-name ;
Access member functions: object_name.memberfunction(actual_parameters);
The following is an example of creating an object of type ’item’ and invoking its member function.
void main ( )
{ item x; // creating an object of type item
x. getdata (20,20.5);
x put data ( );
}
Memory allocation for objects:-
For each object of a class a separate copy of data members and one copy of member functions is created. For each object a separate memory is allocated and the address of that memory is stored in this pointer. By using this pointer the unique copy of member function of all the objects of a class are identified. This pointer is passed automatically to all the member functions of a class.
Exapmle:
#include<iostream.h>
#include<conio.h>
class sample
{ public:
int a ;
void get()
{ cout<<"\nenter any no:";
cin>>a; }
void show()
{ cout<<"\n value of a="<<a; }
};
//sample a1,a2;
class try
{ public:
int b;
void show()
{ cout<<"enter value of b:";
cin>>b;
cout<<"value of b is"<<b;
a1.a=202; // undefined symbol a1
a1.show(); //undefined symbol a1
}
};
try i1;
void main()
{ sample a1;// if we create object of class here then we can not access its members in class try.
clrscr();
i1.show();
a1.get();
a1.show();
getch();
}
Exapmle 2:
void main()
{
clrscr();
class sample
{ private:
int a ;
void show()
{ cout<<"\n**value of a="<<a;
cin>>a; }
};
sample a1,a2;
a1.show(); //error ,although the calss is define inside the main() but its members are private ,so cannot
getch(); accessible outside of the class.
}
Labels: C++