Unit-2 (Topics)
• CLASSES AND OBJECTS : Introduction, Classes In C++, Declaring Objects,
Access Specifiers And Their Scope, Member Functions, Outside Member Function
As Inline, Data Hiding or Encapsulation, Classes, Objects and Memory, Static
Member Variables, Static Member Functions Static Object, Array Of Objects,
Objects As Function Arguments, Friend Functions, The Const Member Functions,
The Volatile Member Function, Recursive Member Function, Local Classes, Empty,
Static And Const Classes, Member Function and Non- Member Function,
Overloading Member Functions, Nested Class
Unit-2
CLASSES and OBJECTS
•Class:-
• Class is a concept which is an extension of structure concept in c.
• Class is used to pack data members and member functions together.
• Which was not there in structures (it can handle only dissimilar data members )
• The class has a mechanism to prevent direct access to its
members(data).
• This is the central idea of object oriented programming.
• Class is a keyword which is used in declaration of class .
• Syntax:-
• class <name of the class>
• {
• access specifier:
• Declaration of variables;
• Prototype declaration of function;
• access specifier:
• Prototype declaration of function;
• };
• class item
• {
• private:
• int codeno;
• float price;
• int qty;
• void value();
• Public:
• void show();
• };
Rules for declaration of a class
• class is a keyword.
• The class is followed by class name.
• The class name should follow variable declaration rules.
• The class name should be sensible.
• The declaration of a class is enclosed with curly braces and it is
terminated with semicolon symbol(;).
• The data members and member functions can be declared in two
sections i.e private and public, these are called as access specifiers.
• The private and public keywords are terminated with colon symbol(:)
Object:-
• Object is a class variable.
• Which is declared in main() function.
• The declaration of object is same as declaration of variables of basic data
types.
• Defining objects of the class datatype is know as class instance.
• As and when objects are crated then the memory is allocated to the class
members.
• Syntax :- Classname object name;
• ex :- item a ;
• item obj;
• item *a;
• item obj1,obj2;
• In the above example a, obj, *a, obj1, obj2 are object names( same as
variable naming rules), *a is pointer object declaration.
Properties of Objects:-
• It is individual
• It points to a thing either physical or logical entity i.e identified by the
user.(i.e Class Members)
• It holds data as well as operation method that handle to the data.
• Its scope is limited to the block in which it is defined.
Access specifiers and their scope:-
• C++ allows three types of access specifies, these access specifiers tells
about access possibilities of the data.
• Those are
• public
• private
• protected
• Based on the access specifiers the data members and methods will
behave accordingly.
Public:
Public is a key word, which is used as access specifier , which allows objects to access the member
variables and functions declared inside the class directly.
The public key word is written inside the class
It is terminated with a colon(:) symbol.
Syntax:-
• Class <class name>
• {
• public:
• data members;
• :
• :
• member functions;
• };
•
• Class item
• {
• public:
• int codeno;
• float pirce;
• int qty;
• :
• :
• Void readdata()
• Void display()
• :
• };
Write a program to declare all members of a class as public. Access the
elements using object through member functions
• #include<iostream.h>
• #include<conio.h>
• class item
• {
• public:
• int codeno;
• float price;
• int qty;
•
• void readdata()
• {
• cout<<"n enter codeno, price, qty“<<endl;
• cin>>codeno>>price>>qty;
• }
• void display()
• {
• cout<<"n codeno="<<codeno;
• cout<<"n price="<<price;
• cout<<"n qty="<<qty;
• }
• };
• int main()
• {
• item one;
• one.readdata();
• one.display();
• getch();
• return 0;
• }
Private:
Private is a key word, which is used as access specifier , it is used to prevent direct access of member variables
or function by the object.
The class by default produces this effect.
The private key word is written inside the class
It is terminated with a colon(:) symbol.
• Class <class name>
• {
• private:
• data members;
• :
• :
• member functions;
• };
• Class item
• {
• private:
• int codeno;
• float pirce;
• int qty;
• Void readdata()
• Void display()
• :
• :
• };
Write a program to declare all members of a class as Private. Access the
elements using object through member functions
• #include<iostream.h>
• #include<conio.h>
• class item
• {
• private:
• int codeno;
• float price;
• int qty;
•
• void readdata()
• {
• cout<<"n enter codeno, price, qty“<<endl;
• cin>>codeno>>price>>qty;
• }
• void display()
• {
• cout<<"n codeno="<<codeno;
• cout<<"n price="<<price;
• cout<<"n qty="<<qty;
• }
• };
• int main()
• {
• item one;
• one.readdata();
• one.display();
• getch();
• return 0;
• }
• Output:
• Item: codeno’ is not accessible
• Item: price’ is not accessible
• Item: qty’ is not accessible
Protected
Protected is a key word, which is used as access specifier , it is used to prevent direct access of member
variables or function by the object. (it works in different manner in Inheritance concept)
The protected key word is written inside the class
It is terminated with a colon(:) symbol.
• Class <class name>
• {
• protected:
• data members;
• :
• :
• member functions;
• };
• Class item
• {
• protected:
• int codeno;
• float pirce;
• int qty;
• Void readdata()
• Void display()
• :
• :
• };
Write a program to declare all members of a class as Protected. Access the
elements using object through member functions
• #include<iostream.h>
• #include<conio.h>
• class item
• {
• Protected :
• int codeno;
• float price;
• int qty;
•
• void readdata()
• {
• cout<<"n enter code,price,qty“<<endl;
• cin>>codeno>>price>>qty;
• }
• void display()
• {
• cout<<"n codeno="<<codeno;
• cout<<"n price="<<price;
• cout<<"n qty="<<qty;
• }
• };
• int main()
• {
• item one;
• one.readdata();
• one.display();
• getch();
• return 0;
• }
• Output:
• Item: codeno’ is not accessible
• Item: price’ is not accessible
• Item: qty’ is not accessible
Access limits of class Members
• Access Specifiers Access permission
• Class members Class Object
• Public Allowed Allowed
• Private Allowed Disallowed
• Protected Allowed Disallowed
• The class object can access a public member of the class directly with
out the use of member function.
• The private and protected mechanisms do not allow an object to
access data directly.
• The object can access private or protected members, only through
public member function of the same class.
Write a program to access private members of a class using public member functions.
• #include<iostream.h>
• #include<conio.h>
• Class item
• {
• Private:
• Int codeno;
• float price;
• Int qty;
• Public:
• void show()
• {
• Cout<<“enter codeno,price,qty”<<endl;
• Cin>>codeno>>price>>qty;
• Cout<<“n codeno=“<<codeno;
• Cout<< “n price=“<<price;
• Cout<<“Quantity=“<<qty;
• }
• };
• Int main()
• {
• clrscr();
• Item one;
• one.show();
• getch();
• retrun 0;
• }
• Output:
• Codeno=125
• Price= 195
• Quantity=200
• In the above program, the member function show() is defined inside
the class in public section.
• In main() function object one is declared. We know that an object has
a permission to access the public members of the class.
• The object one invokes the public member function show().
• The public member function can access the private members of the
same class.
• The function show() initialize the private member variables and
displays the contents on the console .
Declaring and defining private members and member functions:
(Nesting of member function)
• In previous example, we learned how to access private data of a class
using public member function
• It is also possible to declare a function in private section like data
variables.
• To execute private member function it must be invoked by public
member function of same class, that means a member functions of a
class can invoke any other member function of its own class.
• Therefore this method of invoking function is known as nesting of
member function.
Write an example program which invokes private member function in a class.
• #include<iostream.h>
• #include<conio.h>
• Class item
• {
• Private:
• int codeno;
• float price;
• int qty;
• void values() 5 // accessing data
• {
• cout<<“etner codeno,price,qty”<<endl;
• cin>>codeno>>price>>qty;
• }
• Public:
• void show() 3 // invoked
• {
• values(); 4 // invoking values() function
• cout<<“n codeno=“<<codeno; 6// printing
• cout<<“n price=“<< price; 7
• cout<<“n qty=“<<qty; 8
• }
• };
• Int main()
• {
• item one
• one . values(); 1// invoking private function, no access
• one . show(); 2 // invoking show function
• getch(); 9
• return 0;
• }
• Output
• Codeno=999
• Price=150.00
• Qty=30
• Explanation:- in the above program the private section of a class item
contains one member function i.e values()
• The function show() is defined in public section.
• In the function main one is an object of class item
• The object one cannot access the private member function
• In order to execute private member function, the private function
must be invoked using public member function.
• In this example the public member function show() invokes private
member function values()
• Note:- in the invoking process of function values the object name and
operator (.) are not used in show() function.
Write a program using class to declare member variable and function as private, public, and protected
sections and make an attempt to access them using object.
• #include<iostream.h>
• Class sample
• {
• Private:
• Int num;
• void show1() 4
• {
• cout<<“n entered in private section”;
• Cout<< “n insert a number “;
• Cin>> num;
• Cout<<“n private Number is = “ <<num;
• }
• Public:
• int num1;
• void show() 2
• {
• show1(); 3
• Cout<<“n inside the public section”; 5
• Cout<<“n enter a number”;
• Cin>> num1;
• Cout<< “ public Number is :”<<num1;
• show2(); 6
• }
• Protected :
• int num2;
• void show2() 7
• {
• cout<<“n inside the protected section “;
• Cout<<“n enter a number”;
• Cin>> num2;
• Cout<<“ protected Number is : ”<<num2;
• }
• };
• Int main()
• {
• sample s;
• s . show(); 1
• getch(); 8
• return 0;
• }
Write a program to calculate simple interest, tide the data elements of the class
using private key word
• #include<iostream.h>
• #include<conio.h>
• Class interest
• {
• private:
• float p,t,r,i;
• public:
• void show()
• {
• Cout<<“n enter p,t,r values”,
• Cin>>p>>t>>r;
• i=(p*t*r)/100;
• Cout<<“the simple interest is=“<< i;
• }
• };
• Int main()
• {
• interest in
• in . show();
• getch();
• return 0;
• }
Member function out side the class:-
• The function defined inside the class are considered as inline functions.
• If a function is small it should be inside the class, if it is large it must be
defined outside the class. ( because to increase the execution speed)
• Rules for declaring outside the class:-
• 1. The prototype of the function must be declared inside the class.
• 2.The function name must be preceded by class name and it’s return type
separated by scope resolution operator (::).
• Syntax:- prototype classname :: function name()
• Ex : void item :: show()
• {
• ---------
• ---------
• }
Write a program which illustrates member function outside the class and access it
• #include<iostream.h>
#include<conio.h>
• class item
• {
• private:
int codeno;
float price;
int qty;
public:
void show(); // prototype declaration
};
• void item :: show() // function out side the class
• {
• Cout<<“enter codeno,price,qty”<<endl;
• Cin>>codeno>>price>>qty;
• Cout<<“ n Code no=“ << codeno;
• Cout<<“n price=“<<price;
• Cout<<“n qty=“<< qty;
• }
• Int main()
• {
• item one;
• one.show();
• getch();
• return 0;
• }
Write a program which illustrates declaration of functions outside the class and access the data.
• #include<iostream.h>
• #include<conio.h>
• class item
• {
• private:
• int codeno;
• float price;
• int qty;
public:
• void readdata();
• void display();
• };
• void item :: readdata()
• {
• cout<<"n enter code,price,qty“<<endl;
• cin>>codeno>>price>>qty;
• }
•
• void item :: display()
• {
• cout<<"n codeno="<<codeno;
• cout<<"n price="<<price;
• cout<<"n qty="<<qty;
• }
• int main()
• {
• item one;
• one.readdata();
• one.display();
• getch();
• return 0;
• }
Array of objects :- Arrays are collection of similar data types, so we can create an array of objects .
Array of elements are stored in continuous memory locations.
Write an example program to declare array of objects, read and display the content of 3 players.
• #include< iostream.h>
• class player
• {
• Private:
• char name[20];
• int age;
• Public:
• void input (void);
• void display(void);
• };
• void player :: display()
• {
• cout<<“n PLAYER NAME:”<<name;
• Cout<<“n AGE:”<<age;
• }
• void player :: input( )
• {
• Cout<< “n Enter player name: ”;
• Cin>>name;
• Cout<<“n Enter age: ”;
• Cin>>age;
• }
• Int main()
• {
• player pl [3] ;
• cout<<“n Entering name and age of 3 players ”;
• for( int i=0; i<3; i++)
• pl [i] . input();
• for( i=0; i<3; i++)
• pl [i] . display();
• getch();
• return 0;
• }
Objects as function arguments :-
• Similar to variables , objects can be passed to functions, there are 3 methods to
pass objects as functional arguments.
• Pass by value ( pass by object)
• Pass by address ( pass the address of object)
• Pass by reference ( pass the reference of an object )
• Pass by object:- A copy of object ( actual object ) is sent to function and assigned
to the object of callee (formal object). Both actual and formal copies of objects
are stored at different memory locations. Therefore changes made in formal
object are not reflected to actual object.
• Pass by address :- In this model address of object is explicitly sent to function.
Therefore, the duplication of object is prevented.(changes can be updated)
• Pass by reference:- in this model alias or reference object is used. Address of
object is implicitly sent to function. Therefore here also the duplication of object
is prevented.(changes can be updated)
Write an example program which illustrates object as function argument, in call by object.
• #include<iostream.h>
• #include<conio.h>
• class lifetime
• {
• private:
• int mnfyr, expyr, lftyr;
• public:
• void getyrs()
• {
• cout<<" enter manufacture year"<<endl;
• cin>>mnfyr;
• cout<<" enter expiry year"<<endl;
• cin>>expyr;
• }
• void lifeperiod(lifetime b1);
• };
• void lifetime :: lifeperiod (lifetime b1)
• {
• lftyr=b1.expyr - b1.mnfyr;
• cout<<"Life time of the product is :"<<lftyr<<" years"<<endl;
• }
• int main()
• {
• clrscr();
• lifetime a1;
• a1.getyrs();
• a1.lifeperiod (a1);
• getch();
• return 0;
• }
• In the above program “class lifetime” is declared with three member
integer variables, the function “getyrs()” read the values from the user.
• The function “lifeperiod()” calculates the difference between the two
integer values.
• In the main() function “a1” is an object to the class lifetime.
• The object “a1” allows the function’s “getyrs()” as well as “lifeperiod()”
• When it is calling with “lifeperiod()” function it is passing an object of
“a1”
• When the defined method is receiving with an object name “b1”
• Then it calculates and prints the result.
Write an example program which illustrates object as function argument, in call by object address.
• #include<iostream.h>
• #include<conio.h>
• class lifetime
• {
• private:
• int mnfyr, expyr, lftyr;
• public:
• void getyrs()
• {
• cout<<" enter manufacture year"<<endl;
• cin>>mnfyr;
• cout<<" enter expiry year"<<endl;
• cin>>expyr;
• }
• void lifeperiod(lifetime *b1);
• };
• void lifetime :: lifeperiod(lifetime *b1)
• {
• lftyr = b1 → expyr - b1 → mnfyr;
• cout<<"Lifetime of the product is :"<<lftyr<<" years"<<endl;
• }
• int main()
• {
• clrscr();
• lifetime a1;
• a1.getyrs();
• a1.lifeperiod( &a1);
• getch();
• return 0;
• }
Write an example program which illustrates object as function argument, in call by reference object .
• #include<iostream.h>
• #include<conio.h>
• class lifetime
• {
• private:
• int mnfyr, expyr, lftyr;
• public:
• void getyrs()
• {
• cout<<" enter manufacture year"<<endl;
• cin>>mnfyr;
• cout<<" enter expiry year"<<endl;
• cin>>expyr;
• }
• void lifeperiod(lifetime &b1);
• };
• void lifetime :: lifeperiod(lifetime &b1)
• {
• lftyr=b1. expyr - b1. mnfyr;
• cout<<"Lifetme of the product is :"<<lftyr<<" years"<<endl;
• }
• int main()
• {
• clrscr();
• lifetime a1;
• a1. getyrs();
• a1. lifeperiod( a1);
• getch();
• return 0;
• }
Friend Function:
• The central idea of encapsulation and data hiding concept is that any non-member function has
no access permission to the private data of the class. The private members of the class are
accessed only from member functions of that class.
• C++ allows a mechanism in which a non-member function has access permission to the private
members of the class.
• This can be done by declaring a non-member function as “friend” to the class, then private data
to be accessed.
• Here “friend” is a keyword.
Syntax:
• class <class name>
{
private:
data members;
:
member functions;
public:
member functions;
friend datatype non-member function( class name friend function object );
};
Write an example program to access private data using non-member function with the
help of friend function in one class.
• #include<iostream.h>
• #inlcude<conio.h>
• Class Account
• {
• Private:
char name[20];
• Int acno;
• float bal;
• Public:
• void read()
• {
• cout<<“n Enter name, acno,and balance”;
• cin>>name>>acno>>bal;
• }
• friend void showbal(Account a); // making friend
• };
• void showbal(Account a) // non-member function
• {
• Cout<<“n Balance of A/C no :”<<a.acno<<“is Rs”<<a.bal;
• }
• Int main()
• {
• Account ac;
• ac.read();
• showbal(ac); // call to friend function ,passing an object
• getch();
• return 0;
• }
•
• In the above syntax the keyword friend must be proceed the declaration.
• The friend function can be defined at any place in program like global function.
• The friend function can be declared as friend function in one or more class.
• The scope access operator must not preceded in definition of friend function
• The declaration of friend function is done inside the class in private or public part as a function.
• The friend functions use objects as arguments.
• Unlike member functions of class, the friend function cannot access the members directly.
• On the other hand it uses object and dot(.) operator to access the private and public member variables of the
class.
• By default friendship is not shred (not mutual).
• For example , class x is declared as friend of y. this does not mean that y has privilege to access the private
members of class x.
• The use of friend function is rare, why because, it is violating rule of encapsulation and
data binding.
• The function can be declared in public or private sections without changing its meaning.
Write a program to declare friend function in two classes. Calculate the sum of integers of both the classes using friend Sum()
function.
• #include<iostream.h>
• #include<conio.h>
• Class first;
• Class second
• {
• int s;
• Public :
• void getvalues()
• {
• Cout<<“n enter a number:”;
• Cin>>s;
• }
• Friend void sum(second, first);
• };
• Class first
• {
• Int f;
• public:
• Void getvalues()
• {
• Cout<<“n enter a number:”;
• Cin>>f;
• }
• Friend void sum(second, first);
• };
• Void sum(second d, first t) // it is non member function
• {
• Cout<<“n sum of two numbers:”<<d.s + t.f ;
• }
• Int main()
• {
• Clrscr();
• first a;
• Second b;
• a.getvalues();
• b.getvalues();
• Sum(b,a);
• getch();
• retrun 0;
• }
Write a program to exchange values between two classes. Using friend function.
• #include <iostream.h>
• #include<conio.h>
• Class second;
• Class first
• {
• Int j;
• Public:
• Void input()
• {
• Cout<<“n enter value of j:”;
• Cin>>j;
• }
• Void show(void)
• {
• Cout<<“n value of J=“<<j;
• }
• Friend void change (first &x, second &y);
• };
• Class second
• {
• Int k;
• Public:
• Void input()
• {
• Cout<<“n enter value of k:”;
• Cin>>k;
• }
• Void show(void)
• {
• Cout<<“n value of K=“<<K;
• }
• Friend void change (first &x, second &y);
• };
• Void change ( first &x , second &y)
• {
• Int temp= x.j; output:
• x.j = y.k; enter value of j: 4
• y.k = temp; enter value of k:8
• } After change values are
• Int main() value of j=8
• Clrscr(); value of k=4
• {
• first C1;
• second C2;
• C1.input();
• C2.input();
• Change(C1,C2);
• Cout<<“n After change values are “<<endl;
• C1 . show();
• C2 . show();
• getch();
• return 0;
• }
Friend classes :-
• It is possible to declare one or more functions as friend functions or an entire
class can also be declared as friend class.
• When all the functions need to access another class in such situations we can
declare an entire class as friend class.
• The friend is not transferable or inheritable from one class to another.
• Declaring Class A to be a friend of Class B does not meant Class B a friend of class
A; that is , friendship is not exchangeable.
• The friend classes are applicable when we want to make available private data of
a class to another class. (But it is not good way to write programs in this manner )
Write a program to demonstrate friend class.
• # include<iostream.h>
• #include<conio.h>
• Class cpp;
• Class c
• {
• private :
• int j;
• Public:
• void getvalue()
• {
• j=22;
• }
• friend cpp;
• };
• Class cpp
• {
• Public:
• Void display1( c a)
• {
• cout<<“n J = “<<a.j;
• }
• Void display2(c b)
• {
• Cout<<“n J= “<<b.j;
• }
• };
• Int main()
• {
• clrscr();
• c x;
• cpp y;
• x.getvalue();
• Y.display1(x);
• Y.display2(x);
• getch();
• retrun 0;
• }
• Output
• J=22
• J=22
• In the above program, two classes A and B are declared .
• The class cpp is friend of class c. the member function of Class cpp
can access the data of class c.
• Thus the display() functions displays the values of data members of
both the classes.
Nested Classes:
• C++ allows a nested class concept to access data members form one to other.
• When a class is defined in another class it is know as nesting of classes.
• In nested classes the scope of inner class is restricted by outer class.
• By using scope resolution operator (::) the inner class member function is
accessed.
Write a program to display some message using nested classes.
• #include< iostream.h>
• #include<conio.h>
• Class one
• {
• public:
• Class two
• {
• public:
• Void display()
• {
• cout<<“n This is nested class”;
• }
• };
• };
• Int main()
• {
• clrscr();
• one :: two x;
• x. display();
• getch();
• return 0;
• }
• Output: This is nested class
Local classes :-
• When classes are declared inside the function then such classes are called as local
classes.
• The local classes have access permission to global variables as well as static
variables.
• The global variables need to be accessed using scope access operator when the
class itself contains member variables with same name as global variable.
• The local classes should not have static data member and static member
functions.
• If at all they are declared, the compiler provides an error message.
Write a program to define classes inside and outside main() function and access the elements
• #include<iostream.h>
• #include<conio.h>
• class A
• {
• private:
• int a;
• Public:
• void get()
• {
• cout<<“n enter value for a :”;
• cin>>a;
• }
• Void show()
• {
• cout<<“ a= “<<a;
• }
• };
• Int main()
• {
• clrscr();
• class B
• {
• Private :
• int b;
• Public:
• void get()
• {
• cout<<“n enter value for b:”;
• cin>>b;
• }
• Void show()
• {
• cout<<“ b= “ << b;
• }
• };
• A j;
• B k;
• J.get(); out put:
• K.get(); enter value of a: 8
• J.show(); enter value of b: 9
• K.show(); a=8 b=9
• getch();
• return 0 ;
• }
Write a program to declare global variables, read and display data using member
functions
• #include<iostream.h>
• #include<conio.h>
• Int j,k,l,m; // global variable
• Class A
• {
• Private:
• Int a;
• Int j;
• Public:
• Void get()
• {
• Cout<<“n enter values for a,j,j and k”;
• Cin>>a>>j>>::j>>k;
• }
• Void show()
• {
• Cout<<“n<<“a=“<<a<<“j=“<<j<<“:: j”<<::j<<“k=“<<k;
• }
• };
• Int main()
• {
• Clrscr();
• Class B
• {
• Int b;
• Int l;
• Public:
• Void get()
• {
• Cout<<“n enter values of b,l,l and m;
• Cin>>b>>l>>:: l>>m;
• }
• Void show()
• {
• Cout<<“n b=“<<b<<“l =“<<l<<“:: l=“<<::l<<“m=“<<m;
• }
• };
• A x;
• B y;
• x.get();
• y.get();
• x.show();
• y.show();
• getch();
• return 0;
• }
• Output:
• Enter value for a , j, j, and k: 1 2 3 4
• Enter values of b , l , l, and m: 5 6 4 3
• a=1 b=2 ::j=3 k=4
• b=5 l=6 ::l=4 m=3
class and object C++ language chapter 2.pptx

class and object C++ language chapter 2.pptx

  • 1.
    Unit-2 (Topics) • CLASSESAND OBJECTS : Introduction, Classes In C++, Declaring Objects, Access Specifiers And Their Scope, Member Functions, Outside Member Function As Inline, Data Hiding or Encapsulation, Classes, Objects and Memory, Static Member Variables, Static Member Functions Static Object, Array Of Objects, Objects As Function Arguments, Friend Functions, The Const Member Functions, The Volatile Member Function, Recursive Member Function, Local Classes, Empty, Static And Const Classes, Member Function and Non- Member Function, Overloading Member Functions, Nested Class
  • 2.
    Unit-2 CLASSES and OBJECTS •Class:- •Class is a concept which is an extension of structure concept in c. • Class is used to pack data members and member functions together. • Which was not there in structures (it can handle only dissimilar data members ) • The class has a mechanism to prevent direct access to its members(data). • This is the central idea of object oriented programming. • Class is a keyword which is used in declaration of class .
  • 3.
    • Syntax:- • class<name of the class> • { • access specifier: • Declaration of variables; • Prototype declaration of function; • access specifier: • Prototype declaration of function; • }; • class item • { • private: • int codeno; • float price; • int qty; • void value(); • Public: • void show(); • };
  • 4.
    Rules for declarationof a class • class is a keyword. • The class is followed by class name. • The class name should follow variable declaration rules. • The class name should be sensible. • The declaration of a class is enclosed with curly braces and it is terminated with semicolon symbol(;). • The data members and member functions can be declared in two sections i.e private and public, these are called as access specifiers. • The private and public keywords are terminated with colon symbol(:)
  • 5.
    Object:- • Object isa class variable. • Which is declared in main() function. • The declaration of object is same as declaration of variables of basic data types. • Defining objects of the class datatype is know as class instance. • As and when objects are crated then the memory is allocated to the class members. • Syntax :- Classname object name; • ex :- item a ; • item obj; • item *a; • item obj1,obj2; • In the above example a, obj, *a, obj1, obj2 are object names( same as variable naming rules), *a is pointer object declaration.
  • 6.
    Properties of Objects:- •It is individual • It points to a thing either physical or logical entity i.e identified by the user.(i.e Class Members) • It holds data as well as operation method that handle to the data. • Its scope is limited to the block in which it is defined.
  • 7.
    Access specifiers andtheir scope:- • C++ allows three types of access specifies, these access specifiers tells about access possibilities of the data. • Those are • public • private • protected • Based on the access specifiers the data members and methods will behave accordingly.
  • 8.
    Public: Public is akey word, which is used as access specifier , which allows objects to access the member variables and functions declared inside the class directly. The public key word is written inside the class It is terminated with a colon(:) symbol. Syntax:- • Class <class name> • { • public: • data members; • : • : • member functions; • }; • • Class item • { • public: • int codeno; • float pirce; • int qty; • : • : • Void readdata() • Void display() • : • };
  • 9.
    Write a programto declare all members of a class as public. Access the elements using object through member functions • #include<iostream.h> • #include<conio.h> • class item • { • public: • int codeno; • float price; • int qty; • • void readdata() • { • cout<<"n enter codeno, price, qty“<<endl; • cin>>codeno>>price>>qty; • } • void display() • { • cout<<"n codeno="<<codeno; • cout<<"n price="<<price; • cout<<"n qty="<<qty; • } • }; • int main() • { • item one; • one.readdata(); • one.display(); • getch(); • return 0; • }
  • 10.
    Private: Private is akey word, which is used as access specifier , it is used to prevent direct access of member variables or function by the object. The class by default produces this effect. The private key word is written inside the class It is terminated with a colon(:) symbol. • Class <class name> • { • private: • data members; • : • : • member functions; • }; • Class item • { • private: • int codeno; • float pirce; • int qty; • Void readdata() • Void display() • : • : • };
  • 11.
    Write a programto declare all members of a class as Private. Access the elements using object through member functions • #include<iostream.h> • #include<conio.h> • class item • { • private: • int codeno; • float price; • int qty; • • void readdata() • { • cout<<"n enter codeno, price, qty“<<endl; • cin>>codeno>>price>>qty; • } • void display() • { • cout<<"n codeno="<<codeno; • cout<<"n price="<<price; • cout<<"n qty="<<qty; • } • }; • int main() • { • item one; • one.readdata(); • one.display(); • getch(); • return 0; • } • Output: • Item: codeno’ is not accessible • Item: price’ is not accessible • Item: qty’ is not accessible
  • 12.
    Protected Protected is akey word, which is used as access specifier , it is used to prevent direct access of member variables or function by the object. (it works in different manner in Inheritance concept) The protected key word is written inside the class It is terminated with a colon(:) symbol. • Class <class name> • { • protected: • data members; • : • : • member functions; • }; • Class item • { • protected: • int codeno; • float pirce; • int qty; • Void readdata() • Void display() • : • : • };
  • 13.
    Write a programto declare all members of a class as Protected. Access the elements using object through member functions • #include<iostream.h> • #include<conio.h> • class item • { • Protected : • int codeno; • float price; • int qty; • • void readdata() • { • cout<<"n enter code,price,qty“<<endl; • cin>>codeno>>price>>qty; • } • void display() • { • cout<<"n codeno="<<codeno; • cout<<"n price="<<price; • cout<<"n qty="<<qty; • } • }; • int main() • { • item one; • one.readdata(); • one.display(); • getch(); • return 0; • } • Output: • Item: codeno’ is not accessible • Item: price’ is not accessible • Item: qty’ is not accessible
  • 14.
    Access limits ofclass Members • Access Specifiers Access permission • Class members Class Object • Public Allowed Allowed • Private Allowed Disallowed • Protected Allowed Disallowed • The class object can access a public member of the class directly with out the use of member function. • The private and protected mechanisms do not allow an object to access data directly. • The object can access private or protected members, only through public member function of the same class.
  • 15.
    Write a programto access private members of a class using public member functions. • #include<iostream.h> • #include<conio.h> • Class item • { • Private: • Int codeno; • float price; • Int qty; • Public: • void show() • { • Cout<<“enter codeno,price,qty”<<endl; • Cin>>codeno>>price>>qty; • Cout<<“n codeno=“<<codeno; • Cout<< “n price=“<<price; • Cout<<“Quantity=“<<qty; • } • }; • Int main() • { • clrscr(); • Item one; • one.show(); • getch(); • retrun 0; • } • Output: • Codeno=125 • Price= 195 • Quantity=200
  • 16.
    • In theabove program, the member function show() is defined inside the class in public section. • In main() function object one is declared. We know that an object has a permission to access the public members of the class. • The object one invokes the public member function show(). • The public member function can access the private members of the same class. • The function show() initialize the private member variables and displays the contents on the console .
  • 17.
    Declaring and definingprivate members and member functions: (Nesting of member function) • In previous example, we learned how to access private data of a class using public member function • It is also possible to declare a function in private section like data variables. • To execute private member function it must be invoked by public member function of same class, that means a member functions of a class can invoke any other member function of its own class. • Therefore this method of invoking function is known as nesting of member function.
  • 18.
    Write an exampleprogram which invokes private member function in a class. • #include<iostream.h> • #include<conio.h> • Class item • { • Private: • int codeno; • float price; • int qty; • void values() 5 // accessing data • { • cout<<“etner codeno,price,qty”<<endl; • cin>>codeno>>price>>qty; • } • Public: • void show() 3 // invoked • { • values(); 4 // invoking values() function • cout<<“n codeno=“<<codeno; 6// printing • cout<<“n price=“<< price; 7 • cout<<“n qty=“<<qty; 8 • } • }; • Int main() • { • item one • one . values(); 1// invoking private function, no access • one . show(); 2 // invoking show function • getch(); 9 • return 0; • } • Output • Codeno=999 • Price=150.00 • Qty=30
  • 19.
    • Explanation:- inthe above program the private section of a class item contains one member function i.e values() • The function show() is defined in public section. • In the function main one is an object of class item • The object one cannot access the private member function • In order to execute private member function, the private function must be invoked using public member function. • In this example the public member function show() invokes private member function values() • Note:- in the invoking process of function values the object name and operator (.) are not used in show() function.
  • 20.
    Write a programusing class to declare member variable and function as private, public, and protected sections and make an attempt to access them using object. • #include<iostream.h> • Class sample • { • Private: • Int num; • void show1() 4 • { • cout<<“n entered in private section”; • Cout<< “n insert a number “; • Cin>> num; • Cout<<“n private Number is = “ <<num; • } • Public: • int num1; • void show() 2 • { • show1(); 3 • Cout<<“n inside the public section”; 5 • Cout<<“n enter a number”; • Cin>> num1; • Cout<< “ public Number is :”<<num1; • show2(); 6 • } • Protected : • int num2; • void show2() 7 • { • cout<<“n inside the protected section “; • Cout<<“n enter a number”; • Cin>> num2; • Cout<<“ protected Number is : ”<<num2; • } • }; • Int main() • { • sample s; • s . show(); 1 • getch(); 8 • return 0; • }
  • 21.
    Write a programto calculate simple interest, tide the data elements of the class using private key word • #include<iostream.h> • #include<conio.h> • Class interest • { • private: • float p,t,r,i; • public: • void show() • { • Cout<<“n enter p,t,r values”, • Cin>>p>>t>>r; • i=(p*t*r)/100; • Cout<<“the simple interest is=“<< i; • } • }; • Int main() • { • interest in • in . show(); • getch(); • return 0; • }
  • 22.
    Member function outside the class:- • The function defined inside the class are considered as inline functions. • If a function is small it should be inside the class, if it is large it must be defined outside the class. ( because to increase the execution speed) • Rules for declaring outside the class:- • 1. The prototype of the function must be declared inside the class. • 2.The function name must be preceded by class name and it’s return type separated by scope resolution operator (::). • Syntax:- prototype classname :: function name() • Ex : void item :: show() • { • --------- • --------- • }
  • 23.
    Write a programwhich illustrates member function outside the class and access it • #include<iostream.h> #include<conio.h> • class item • { • private: int codeno; float price; int qty; public: void show(); // prototype declaration }; • void item :: show() // function out side the class • { • Cout<<“enter codeno,price,qty”<<endl; • Cin>>codeno>>price>>qty; • Cout<<“ n Code no=“ << codeno; • Cout<<“n price=“<<price; • Cout<<“n qty=“<< qty; • } • Int main() • { • item one; • one.show(); • getch(); • return 0; • }
  • 24.
    Write a programwhich illustrates declaration of functions outside the class and access the data. • #include<iostream.h> • #include<conio.h> • class item • { • private: • int codeno; • float price; • int qty; public: • void readdata(); • void display(); • }; • void item :: readdata() • { • cout<<"n enter code,price,qty“<<endl; • cin>>codeno>>price>>qty; • } • • void item :: display() • { • cout<<"n codeno="<<codeno; • cout<<"n price="<<price; • cout<<"n qty="<<qty; • } • int main() • { • item one; • one.readdata(); • one.display(); • getch(); • return 0; • }
  • 25.
    Array of objects:- Arrays are collection of similar data types, so we can create an array of objects . Array of elements are stored in continuous memory locations. Write an example program to declare array of objects, read and display the content of 3 players. • #include< iostream.h> • class player • { • Private: • char name[20]; • int age; • Public: • void input (void); • void display(void); • }; • void player :: display() • { • cout<<“n PLAYER NAME:”<<name; • Cout<<“n AGE:”<<age; • } • void player :: input( ) • { • Cout<< “n Enter player name: ”; • Cin>>name; • Cout<<“n Enter age: ”; • Cin>>age; • } • Int main() • { • player pl [3] ; • cout<<“n Entering name and age of 3 players ”; • for( int i=0; i<3; i++) • pl [i] . input(); • for( i=0; i<3; i++) • pl [i] . display(); • getch(); • return 0; • }
  • 26.
    Objects as functionarguments :- • Similar to variables , objects can be passed to functions, there are 3 methods to pass objects as functional arguments. • Pass by value ( pass by object) • Pass by address ( pass the address of object) • Pass by reference ( pass the reference of an object ) • Pass by object:- A copy of object ( actual object ) is sent to function and assigned to the object of callee (formal object). Both actual and formal copies of objects are stored at different memory locations. Therefore changes made in formal object are not reflected to actual object. • Pass by address :- In this model address of object is explicitly sent to function. Therefore, the duplication of object is prevented.(changes can be updated) • Pass by reference:- in this model alias or reference object is used. Address of object is implicitly sent to function. Therefore here also the duplication of object is prevented.(changes can be updated)
  • 27.
    Write an exampleprogram which illustrates object as function argument, in call by object. • #include<iostream.h> • #include<conio.h> • class lifetime • { • private: • int mnfyr, expyr, lftyr; • public: • void getyrs() • { • cout<<" enter manufacture year"<<endl; • cin>>mnfyr; • cout<<" enter expiry year"<<endl; • cin>>expyr; • } • void lifeperiod(lifetime b1); • }; • void lifetime :: lifeperiod (lifetime b1) • { • lftyr=b1.expyr - b1.mnfyr; • cout<<"Life time of the product is :"<<lftyr<<" years"<<endl; • } • int main() • { • clrscr(); • lifetime a1; • a1.getyrs(); • a1.lifeperiod (a1); • getch(); • return 0; • }
  • 28.
    • In theabove program “class lifetime” is declared with three member integer variables, the function “getyrs()” read the values from the user. • The function “lifeperiod()” calculates the difference between the two integer values. • In the main() function “a1” is an object to the class lifetime. • The object “a1” allows the function’s “getyrs()” as well as “lifeperiod()” • When it is calling with “lifeperiod()” function it is passing an object of “a1” • When the defined method is receiving with an object name “b1” • Then it calculates and prints the result.
  • 29.
    Write an exampleprogram which illustrates object as function argument, in call by object address. • #include<iostream.h> • #include<conio.h> • class lifetime • { • private: • int mnfyr, expyr, lftyr; • public: • void getyrs() • { • cout<<" enter manufacture year"<<endl; • cin>>mnfyr; • cout<<" enter expiry year"<<endl; • cin>>expyr; • } • void lifeperiod(lifetime *b1); • }; • void lifetime :: lifeperiod(lifetime *b1) • { • lftyr = b1 → expyr - b1 → mnfyr; • cout<<"Lifetime of the product is :"<<lftyr<<" years"<<endl; • } • int main() • { • clrscr(); • lifetime a1; • a1.getyrs(); • a1.lifeperiod( &a1); • getch(); • return 0; • }
  • 30.
    Write an exampleprogram which illustrates object as function argument, in call by reference object . • #include<iostream.h> • #include<conio.h> • class lifetime • { • private: • int mnfyr, expyr, lftyr; • public: • void getyrs() • { • cout<<" enter manufacture year"<<endl; • cin>>mnfyr; • cout<<" enter expiry year"<<endl; • cin>>expyr; • } • void lifeperiod(lifetime &b1); • }; • void lifetime :: lifeperiod(lifetime &b1) • { • lftyr=b1. expyr - b1. mnfyr; • cout<<"Lifetme of the product is :"<<lftyr<<" years"<<endl; • } • int main() • { • clrscr(); • lifetime a1; • a1. getyrs(); • a1. lifeperiod( a1); • getch(); • return 0; • }
  • 31.
    Friend Function: • Thecentral idea of encapsulation and data hiding concept is that any non-member function has no access permission to the private data of the class. The private members of the class are accessed only from member functions of that class. • C++ allows a mechanism in which a non-member function has access permission to the private members of the class. • This can be done by declaring a non-member function as “friend” to the class, then private data to be accessed. • Here “friend” is a keyword. Syntax: • class <class name> { private: data members; : member functions; public: member functions; friend datatype non-member function( class name friend function object ); };
  • 32.
    Write an exampleprogram to access private data using non-member function with the help of friend function in one class. • #include<iostream.h> • #inlcude<conio.h> • Class Account • { • Private: char name[20]; • Int acno; • float bal; • Public: • void read() • { • cout<<“n Enter name, acno,and balance”; • cin>>name>>acno>>bal; • } • friend void showbal(Account a); // making friend • }; • void showbal(Account a) // non-member function • { • Cout<<“n Balance of A/C no :”<<a.acno<<“is Rs”<<a.bal; • } • Int main() • { • Account ac; • ac.read(); • showbal(ac); // call to friend function ,passing an object • getch(); • return 0; • } •
  • 33.
    • In theabove syntax the keyword friend must be proceed the declaration. • The friend function can be defined at any place in program like global function. • The friend function can be declared as friend function in one or more class. • The scope access operator must not preceded in definition of friend function • The declaration of friend function is done inside the class in private or public part as a function. • The friend functions use objects as arguments. • Unlike member functions of class, the friend function cannot access the members directly. • On the other hand it uses object and dot(.) operator to access the private and public member variables of the class. • By default friendship is not shred (not mutual). • For example , class x is declared as friend of y. this does not mean that y has privilege to access the private members of class x. • The use of friend function is rare, why because, it is violating rule of encapsulation and data binding. • The function can be declared in public or private sections without changing its meaning.
  • 34.
    Write a programto declare friend function in two classes. Calculate the sum of integers of both the classes using friend Sum() function. • #include<iostream.h> • #include<conio.h> • Class first; • Class second • { • int s; • Public : • void getvalues() • { • Cout<<“n enter a number:”; • Cin>>s; • } • Friend void sum(second, first); • }; • Class first • { • Int f; • public: • Void getvalues() • { • Cout<<“n enter a number:”; • Cin>>f; • } • Friend void sum(second, first); • }; • Void sum(second d, first t) // it is non member function • { • Cout<<“n sum of two numbers:”<<d.s + t.f ; • } • Int main() • { • Clrscr(); • first a; • Second b; • a.getvalues(); • b.getvalues(); • Sum(b,a); • getch(); • retrun 0; • }
  • 35.
    Write a programto exchange values between two classes. Using friend function. • #include <iostream.h> • #include<conio.h> • Class second; • Class first • { • Int j; • Public: • Void input() • { • Cout<<“n enter value of j:”; • Cin>>j; • } • Void show(void) • { • Cout<<“n value of J=“<<j; • } • Friend void change (first &x, second &y); • }; • Class second • { • Int k; • Public: • Void input() • { • Cout<<“n enter value of k:”; • Cin>>k; • } • Void show(void) • { • Cout<<“n value of K=“<<K; • } • Friend void change (first &x, second &y); • }; • Void change ( first &x , second &y) • { • Int temp= x.j; output: • x.j = y.k; enter value of j: 4 • y.k = temp; enter value of k:8 • } After change values are • Int main() value of j=8 • Clrscr(); value of k=4 • { • first C1; • second C2; • C1.input(); • C2.input(); • Change(C1,C2); • Cout<<“n After change values are “<<endl; • C1 . show(); • C2 . show(); • getch(); • return 0; • }
  • 36.
    Friend classes :- •It is possible to declare one or more functions as friend functions or an entire class can also be declared as friend class. • When all the functions need to access another class in such situations we can declare an entire class as friend class. • The friend is not transferable or inheritable from one class to another. • Declaring Class A to be a friend of Class B does not meant Class B a friend of class A; that is , friendship is not exchangeable. • The friend classes are applicable when we want to make available private data of a class to another class. (But it is not good way to write programs in this manner )
  • 37.
    Write a programto demonstrate friend class. • # include<iostream.h> • #include<conio.h> • Class cpp; • Class c • { • private : • int j; • Public: • void getvalue() • { • j=22; • } • friend cpp; • }; • Class cpp • { • Public: • Void display1( c a) • { • cout<<“n J = “<<a.j; • } • Void display2(c b) • { • Cout<<“n J= “<<b.j; • } • }; • Int main() • { • clrscr(); • c x; • cpp y; • x.getvalue(); • Y.display1(x); • Y.display2(x); • getch(); • retrun 0; • } • Output • J=22 • J=22
  • 38.
    • In theabove program, two classes A and B are declared . • The class cpp is friend of class c. the member function of Class cpp can access the data of class c. • Thus the display() functions displays the values of data members of both the classes.
  • 39.
    Nested Classes: • C++allows a nested class concept to access data members form one to other. • When a class is defined in another class it is know as nesting of classes. • In nested classes the scope of inner class is restricted by outer class. • By using scope resolution operator (::) the inner class member function is accessed.
  • 40.
    Write a programto display some message using nested classes. • #include< iostream.h> • #include<conio.h> • Class one • { • public: • Class two • { • public: • Void display() • { • cout<<“n This is nested class”; • } • }; • }; • Int main() • { • clrscr(); • one :: two x; • x. display(); • getch(); • return 0; • } • Output: This is nested class
  • 41.
    Local classes :- •When classes are declared inside the function then such classes are called as local classes. • The local classes have access permission to global variables as well as static variables. • The global variables need to be accessed using scope access operator when the class itself contains member variables with same name as global variable. • The local classes should not have static data member and static member functions. • If at all they are declared, the compiler provides an error message.
  • 42.
    Write a programto define classes inside and outside main() function and access the elements • #include<iostream.h> • #include<conio.h> • class A • { • private: • int a; • Public: • void get() • { • cout<<“n enter value for a :”; • cin>>a; • } • Void show() • { • cout<<“ a= “<<a; • } • }; • Int main() • { • clrscr(); • class B • { • Private : • int b; • Public: • void get() • { • cout<<“n enter value for b:”; • cin>>b; • } • Void show() • { • cout<<“ b= “ << b; • } • }; • A j; • B k; • J.get(); out put: • K.get(); enter value of a: 8 • J.show(); enter value of b: 9 • K.show(); a=8 b=9 • getch(); • return 0 ; • }
  • 43.
    Write a programto declare global variables, read and display data using member functions • #include<iostream.h> • #include<conio.h> • Int j,k,l,m; // global variable • Class A • { • Private: • Int a; • Int j; • Public: • Void get() • { • Cout<<“n enter values for a,j,j and k”; • Cin>>a>>j>>::j>>k; • } • Void show() • { • Cout<<“n<<“a=“<<a<<“j=“<<j<<“:: j”<<::j<<“k=“<<k; • } • }; • Int main() • { • Clrscr(); • Class B • { • Int b; • Int l; • Public: • Void get() • { • Cout<<“n enter values of b,l,l and m; • Cin>>b>>l>>:: l>>m; • } • Void show() • { • Cout<<“n b=“<<b<<“l =“<<l<<“:: l=“<<::l<<“m=“<<m; • } • }; • A x; • B y; • x.get(); • y.get(); • x.show(); • y.show(); • getch(); • return 0; • }
  • 44.
    • Output: • Entervalue for a , j, j, and k: 1 2 3 4 • Enter values of b , l , l, and m: 5 6 4 3 • a=1 b=2 ::j=3 k=4 • b=5 l=6 ::l=4 m=3