Class is a way to bind data and its associated Function together .It also allows data and function to be hidden ,if necessary ,from External User .
The class Member that have been declare as private can be access only from within the class . on the other Hand Public data and function can be access from outside the class also .
By default the member of class is private .
The class Member that have been declare as private can be access only from within the class . on the other Hand Public data and function can be access from outside the class also .
By default the member of class is private .
A simple Class Example :
Creating An Object :
create a variable x of type "test" , In C++ Class variable is known as Object . Therefore x is called an object of type "test" .
- test x,y,x //declaring class object
Here x y and z is object of type test
Accessing Class Member :-
private data of Class can be access only through the member function of that Class.
Public data and function can be access using "."operator
Example :
object-name.function-name(actual arguments)
- test x; //create object
- x.assign() //access function using . operator
- x.print()
Defining Class Member function :
It can be define inside or outside the class .
member function define inside is always inline ( you mention or not ) .
Defining Member Function outside Class .
return-type class-name :: function-name(arguments){
A C++ Program With Class :
- /*
- Introduction to class in C++
- http://beginer2cs.blogspot.com
- */
- #include<iostream>
- using namespace std;
- class test{
- private: //declaring private data
- int a;
- float b;
- public: //declaring public data and func
- void assign(void); //declare member func
- void print(void);
- };
- /*
- "::" called Scope resolution operator
- */
- void test::assign(){ //defining member func
- int x;
- float y;
- cout<<"Enter value of a : ";
- cin>>x;
- cout<<"Enter value of b: ";
- cin>>y;
- a=x;
- b=y;
- }
- void test::print(){
- cout<<" a :- "<<a;
- cout<<"\n b :- "<<b;
- }
- main(){
- test x; //creating an object of class x
- x.assign(); //calling public func of class test
- /*we can't directly access private variable and data
- using "." operator . only public function of same
- class can access it and modify it
- */
- x.print();
- }
Output :
No comments:
Post a Comment
THANKS FOR UR GREAT COMMENT