Home | | Computer Science 11th std | Example C++ Programs: Classes and objects

Chapter: 11th Computer Science : Chapter 14 : Classes and objects

Example C++ Programs: Classes and objects

Computer Science : Classes and objects - Example C++ Program: Classes and objects

Illustration 14.1 Inline and Outline member function

Absence of access specifier means that members are private by default..  

# include <iostream>         

using namespace std; 

class Box

{   

      double width; // no access specifier mentioned

public:  

      double length;  

void printWidth( ) //inline member function definition

      {    

           cout<<”\n The width of the box is...”<<width;

      }

void setWidth( double w ); //prototype of the function

};

void Box :: setWidth(double w) // outline member function definition

{

width=w;

}

int main( )

{

Box b;                   // object for class Box

b.setWidth(10.0);            // Use member function to set the width.

b.printWidth( );                        //Use member function to print the width.

return 0;

}

Output:

The width of the box is... 10


Illustration 14.2 The use of local object

A global object can be declared only for global class. If a class definition is specified outside the body of all functions in a program then it is called global class

#include <iostream>

#include <conio>

using namespace

std class add          //Global class

{

int a,b;

public:

int sum;

void getdata()

{

a=5;

b=10;

sum = a+b;

}

a1;

add a2;

int main()

{

add a3;       //Local object for a global class

a1.getdata();

a2.getdata();

a3.getdata();  //public data member accessed from outside the class

cout<<a1.sum;

cout<<a2.sum;

cout<<a3.sum;

return 0;

}

Output:

151515


Illustration 14.3 Memory allocation for objects

include <iostream>

using namespace std;

//The members will be allocated with memory space only after the creation of the class type object

class product

{

      int code, quantity;

      float price;

      public:

      void assignData();

      void Print();

};

int main()

{

      product p1, p2;

      cout<<”\n Memory allocation for object p1 ” <<sizeof(p1);

      cout<<”\n Memory allocation for object p2 ” <<sizeof(p2);

      return 0;

}

Output:

Memory allocation for object p1 12

Memory allocation for object p2 12


Illustration 14.4 C++ program to illustrate the communication of object:

Calling a member function of an object is also known as sending message to object or  communication  with  the object.

#include<iostream>

using namespace std; 

class compute

{   

       int n1,n2; //private by default

public :

      int n;  

      int add (int a, int b)   //inline member function

       {

      int c=a+b; //int c ; local variable for this function

      return c;

       }

       int prd (int a, int b) //inline member function

      {

      int c=a*b;

      return c;

      }          

};   // end of class specification        

compute c1,c2;     //global object      

int main()

{

      c1.n =c1.add(12,15);  //member function is called

      c2.n =c2.add(8,4);

      cout<<"\n Sum of object-1 "<<c1.n;

      cout<<"\n Sum of object-2 "<<c2.n;

      cout<<"\n Sum of the two objects are "<<c1.n+c2.n;

      c1.n=c1.prd(5,4);

      c2.n=c2.prd(2,5);

      cout<<"\n Product of object-1 "<<c1.n;

      cout<<"\n Product of object-2 "<<c2.n;

      cout<<"\n Product of the two objects are "<<c1.n*c2.n;

      return 0;

}

Output:

Sum of object-1 27

Sum of object-2 12

Sum of the two objects are 39

Product of object-1 20

Product of object-2 10

Product of the two objects are 200


Illustration 14.5 Array of objects

gets () can accept a string with space which is not possible by cin.

#include<iostream> 

#include<stdio.h> 

using namespace std;

class stock 

      int itemno; 

      char itemname[10];  // array as member variable

      float price;

      public: 

      void getdata()

      {

      cin>>itemno>>price;

      gets(itemname);

}

void putdata()

{

      cout<<’\n’<<itemno<<’\t’<<itemname<<’\n’<<price;

}

};

int main()

{

stock s[10];

int i;

cout<<”Enter the details\n”;

      for( i=0;i<10;i++)

           s[i].getdata();

cout<<”\n Item Details\n”;

cout<<”\nITEM NO \t ITEM NAME\t PRICE”<<endl;

      for( i=0;i<10;i++)

           s[i].putdata();

 return 0;

}

Output

Item Details

ITEM NOITEM NAME          PRICE

101     APSARA PENCIL       Price10.5

102     FABER CASTELL PENCIL  Price12.0001

103     NATARAJ PENCIL     Price9.75

201     PILOT V7 PEN            Price50

201     CELLO BUTTERFLOW        Price10

202     PARKER PEN             Price450

202     PILOT FOUNTAIN PEN       Price600

301     APSARA ERASER      Price5

302     FABER CASTELL ERASER Price15.0001

303     NATARAJ ERASER   Price3


Illustration 14.6 Inline Outline and function

 #include<iostream>

 using namespace std

 class sales

 {

      int sno;

       char sname [15];

       float hrwrk,wage,totwage;

 void calcwg( )

 {

        totwage=hrwrk * wage;

 }

public :

       void in_data();

       void out_data();

 };

void sales :: in_data()

{

      wage=75.26;

      totwage=0.0;

      cout<<"\nEnter the salesperson id";cin>>sno;

      cout<<"\nEnter the name" ;gets(sname);

      cout<<"\nEnter the hours worked" ;cin>>hrwrk;

      calcwg(); //member function called inside by another member function

}

void sales :: out_data()

{

      cout<<"\n Wage slip ";

      cout<<"\n ~~~~~~~~ ";

      cout<<"\nID : " << sno;

      cout<<"\nName : " <<sname ;

      cout<<"\nHours worked :" <<hrwrk;

      cout<<"\nTotal Wage :"<<setprecision(2)<<totwage;

}

int main()

{

      sales sal;

      sal.in_data();

      sal.out_data();

      return 0;

}

Output:

Enter the salesperson id 1201

Enter the name ARUL

Enter the hours worked 7

Wage slip

~~~~~~~~

ID : 1201

Name : ARUL

Hours worked :7

Total Wage :526.82


Illustration 14.7 The use of Nesting of Member Function

A member function can call another member function of the same class for that you do not need an object.

#include<iostream>

using namespace std

class nest

{

      int a;

      int square_num( )

      {

           return a* a;

      }

      public:

      void input_num( )

      {

      cout<<”\nEnter a number ”;

      cin>>a;

      }

      int cube_num( )

      {

           return a* a*a;

      }

void disp_num()

{

      int sq=square_num();        //nesting of member function

      int cu=cube_num();  //nesting of member function

      cout<<”\nThe square of “<<a<<” is  ” <<sq;

      cout<<”\nThe cube of “<<a<<” is  ” <<cu;

}

};

int main()

{

      nest n1;

      n1.input_num();

      n1.disp_num();

      return 0;

}

Output:

Enter a number 5

The square of 5 is 25

The cube of 5 is 125


Illustration 14.8 The use of scope resolution operator

Recall :: is also used to identify the class to which a member function belongs to.

#include<iostream>

using namespace std;

int a=100;

class A

{

      int a;

      public:

void fun()

      {

      a=20;

      a+=::a;         //using global variable value

      cout<<a;

} };

int main()

{

      clrscr(); A a1;

      a1.fun();

      retun 0;

}

Output:

120 


Illustration 14.9 C++ program to illustrate how the pass by value method work

we can assign one object to another object, Similar to structure object

#include <iostream>

using namespace std;

class Sample

{

private:

      int num;         

public:

      void set (int x)

      {

      num = x;

      }

void pass(Sample obj1, Sample obj2) //objects are passed

{

      obj1.num=100;        // value of the object is changed inside the function

      obj2.num=200;        // value of the object is changed inside the function

      cout<<"\n\n Changed value of object1 "<<obj1.num;

      cout<<"\n\n Changed value of object2 "<<obj2.num;

}

      void print( )

      {

           cout<<num;

      }

};

int main()

{

      //object declarations

      Sample s1;

      Sample s2;

      Sample s3;

      //assigning values to the data member of objects

      s1.set(10);

      s2.set(20);

      cout<<"\n\t\t Example program for pass by value\n\n\n"; //printing the values before passing the object

      cout<<"\n\nValue of object1 before passing";

      s1.print();

      cout<<"\n\nValue of object2 before passing ";

      s2.print();

      passing object s1 and s2

      s3.pass(s1,s2);

      //printing the values after returning to main

      cout<<"\n\nValue of object1 after passing ";

      s1.print();

      cout<<"\n\nValue of object2 after passing ";

      s2.print();

      return 0;

}

Output:

Example program for PASS BY VALUE

Value of object1 before passing 10

Value of object2 before passing 20

Changed value of object 1 100

Changed value of object 200

Value of object 1 after passing 10

Value of object 2 after passing 20


Illustration 14.10 C++ program to illustrate how the pass by reference method work

#include <iostream>

using namespace std;

class Sample

{

private:

      int num;

public:

void set (int x)

{

      num = x;

}

void pass(Sample &obj1, Sample &obj2) //objects are passed

{

      obj1.num=100;            // value of the object is changed inside the function

      obj2.num=200;            // value of the object is changed inside the function

      cout<<"\n\n Changed value of object1 "<<obj1.num;

      cout<<"\n\n Changed value of object2 "<<obj2.num;

}

      void print()

      {

           cout<<num;

      }

};

int main()

{

      clrscr();

      //object declarations

      Sample s1;

      Sample s2;

      Sample s3;

      //assigning values to the data member of objects

      s1.set(10);

      s2.set(20);

      cout<<"\n\t\t Example program for pass by reference\n\n\n";

      //printing the values before passing the object

      cout<<"\n\nValue of object1 before passing"; s1.print();

      cout<<"\n\nValue of object2 before passing "; s2.print();

      //passing object s1 and s2 s3.pass(s1,s2);

      //printing the values after returning to main

      cout<<"\n\nValue of object1 after passing "; s1.print();

      cout<<"\n\nValue of object2 after passing ";

      s2.print();

      return 0;

}

Output:

Example program for PASS BY REFERENCE

Value of object1 before passing10

Value of object 2 before passing 20

Changed value of object1 100

Changed value of object2 200

Value of object1 after passing 100

Value of object2 after passing 200


Illustration 14.11 C++ program to illustrate how an object is returned to the calling function

#include <iostream>

using namespace std;

class Sample

{

      private:

           int num;

      public:

      void set (int x)

      {

      num = x;

      }

      Sample pass(Sample obj1, Sample obj2) //

      {

      Sample s4;

      s4.num=obj1.num+obj2.num;

      return s4;

      }

      }

      void print()

      {

      cout<<num;

      }

};

int main()

{

      //object declarations

      Sample s1;

      Sample s2;

      Sample s3;

      //assigning values to the data member of objects

      s1.set(10);

      s2.set(20);

      cout<<"\n\t\t Example program for Returning an object \n\n\n";

      //passing object s1 and s2

      s3=s3.pass(s1,s2);

      //printing the values of object

      cout<<"\nThe value of s1.num is ";

      s1.print();

      cout<<"\nThe value of s2.num is ";

      s2.print();

      //printing the sum

      cout<<"\nThe sum s3.num is ";s3.print();

      return 0;

}

Output:

Example program for Returning an object

The value of s1.num is 10

The value of s2.num is 20

The sum s3.num is 30


Illustration 14.12 C++ program to illustrate the nested class

#include<iostream>

using namespace std;

class enclose

{

private:

      int x;

      class nest

      {

private :

      int y;

public:

      int z;

void prn()

{

      y=3;z=2;

      cout<<"\n The product of"<<y<<'*'<<z<<"= "<<y*z<<"\n";

}

}; //inner class definition over

nest n1;

public:

nest n2;

void square()

{

n2.prn(); //inner class member function is called by its object x=2;

      n2.z=4;

      cout<<"\n The product of " <<n2.z<<'*'<<n2.z<<"= "<<n2.z*n2.z<<"\n";

      cout<<"\n The product of " <<x<<'*'<<x<<"= "<<x*x; }

};   //outer class definition over

int main()

{

enclose e;

      e.square();  //outer class member function is called

}

Output:

The product of 3*2=6

The product of 4*4=16

The product of 2*2=4


Illustration 14.13 C++ program to illustrate the containership

#include<iostream>

using namespace std;

class outer

{

      int data;

      public:

      void get();

};

class inner

{

      int value;

      outer ot; // object ot of class outer is declared in class inner

      public:

      void getdata();

};

void outer :: get()

{

      cout<<"\nEnter a value";

      cin>>data;

      cout<<"\nThe given value is "<<data;

}

void inner :: getdata()

{

      cout<<"\nEnter a value";

      cin>>value;

      cout<<"\nThe given value is "<<value;

      ot.get();  //calling of get() of class outer in getdata() of class inner

}

int main()

{

      inner in;

      in.getdata();

      return 0;

}

Output:

Enter a value10

The given value is 10

Enter a value 20

The given value is 20


Illustration 14.14 A constructor defined inside the class specification.

#include<iostream>

using namespace std;

class Sample

{

int i,j;

      public :

int k;

      Sample()

      {

      i=j=k=0;//constructor defined inside the class

      }

};

 

Illustration 14.15 A constructor defined inside the class specification.

#include<iostream>

using namespace std;

class Sample

{

int i,j;

      public :

int k;

      Sample()

      {

      i=j=k=0;//constructor defined inside the class

      }

};

int main()

{

Samples1;

return 0;

}


Illustration 14.16 A constructor defined outside the class specification.

#include<iostream>

using namespace std;

class Data

      {

int p,q;

      public :

int r;

      Data();   //only prototype to be specified here to intimate its access specifier

      };

Data ::Data()

{

      p=q=r=0;                      // constructor defined outside the class

}

int main()

{

      Data d1;

return 0;

}

 

Illustration 14.17 illustrate a constructor defined inside the private visibility.

#include<iostream>

using namespace std;

class X

{

      int num;

      X()

{

      num=k=0;

}

public:

int k;

};

int main()

{

X x;    // The constructor of X cannot accessed by main() because main() is a

      //non member function

      //and the compiler throws error message             [Error] 'X::X()' is private

return 0;

}


Illustration 14.18 illustrate a member function initializes the data member.

After creating the object the getvalue() should be explicitly called to initialize the object.

#include<iostream>

using namespace std;

class Sample

{

      int i, j;

      public :

      int k;

      void getvalue()

      {

      i=j=k=0; //member function

      }

int main()

{

Sample s1;

      s1.getvalue();                        //member function initializes the class object

return 0;

}


Illustration 14.19 illustrate the compiler generated constructor

#include<iostream>

using namespace std;

class Sample

{

      int i, j;

      public:

      int k; //no user defined constructor in this program

      void getvalue()//member function

      {

           i=j=k=0;

      }

};

int main()

{

      Sample s1; //uses the default constructor generated by the compiler

      s1.getvalue();

      return 0;

}

 

Illustration 14.20 to illustrate the constructor and other member function in a class

#include<iostream>

using namespace std;

class simple

{

private:

      int a,b;

public:

simple()

{

      a= 0 ;

      b= 0;

      cout<< "\n Constructor of class-simple ";

}

      void getdata()

      {

      cout<<"\n Enter values for a and b (sample data 6 and 7)... ";

      cin>>a>>b;

      }

      void putdata()

      {

      cout<<"\nThe two integers are... "<<a<<'\t'<< b<<endl;

      cout<<"\n The sum of the variables "<<a<<" + "<<b<<" = "<<a+b;

      }

};

int main()

{

      simple s;

      s.getdata();

      s.putdata();

      return 0;

}

Output:

Constructor of class-simple

Enter values for a and b (sample data 6 and 7)... 6 7

The two integers are... 6         7

The sum of the variables 6 + 7 = 13


Illustration 14.21 to illustrate the Parameterized constructor used for creating objects

#include<iostream>

using namespace std;

class simple

{

private:

      int a,b;

public:

simple(int m, int n)

{

a= m ;

b= n;

cout<< "\n Parameterized Constructor of class-simple "<<endl;

}

void putdata()

{

cout<<"\nThe two integers are... "<<a<<'\t'<< b<<endl;

cout<<"\n The sum of the variables "<<a<<" + "<<b<<" = "<< a+b; }

};

int main()

{

simple s1(10,20),s2(30,45); //Created two objects with different values created

cout<<"\n\t\tObject 1\n";

s1.putdata();

cout<<"\n\t\tObject 2\n";

s2.putdata();

return 0;

}

Output:

Parameterized Constructor of class-simple

Parameterized Constructor of class-simple

Object 1

The two integers are .. 10      20

The sum of the variables 10 + 20 = 30

Object 2

The two integers are... 30      45

The sum of the variables 30 + 45 = 75

 

Illustration 14.22 to illustrate the creation of object with no argument after defining parameterized constructor throws error

Note:- Just like normal function parameterized constructor can also have default arguments.

#include<iostream>

using namespace std;

class simple

{

private:

      int a,b;

public:

simple(int m, int n)

{

a= m ;

b= n;

cout<< "\n Parameterized Constructor of class-simple "<<endl;

}

void putdata()

{

cout<<"\nThe two integers are .. "<<a<<'\t'<< b<<endl;

cout<<"\n The sum of the variables "<<a<<" + "<<b<<" = "<< a+b; }

};

int main()

{

simple s,s1(10,20)      // [Error] no matching function for call to 'simple::simple()'

s1.putdata();

s2.putdata();

return 0;

}

 

Illustration 14.23 to illustrate the default argument in parameterized constructor

#include<iostream>

using namespace std;

class simple

{

private:

int a,b;

public:

simple(int m, int n=100)   //default argument

{

a= m ;

b= n;

cout<< "\n Parameterized Constructor with default argument"<<endl;

}

void putdata()

{

cout<<"\nThe two integers are... "<<a<<'\t'<< b<<endl;

cout<<"\n The sum of the variables "<<a<<" + "<<b<<" = "<< a+b; }

};

int main()

{

simple s1(10,20),s2(50);

cout<<"\n\t\tObject 1 with both values \n";

s1.putdata();

cout<<"\n\t\tObject 2 with one value and one deafult value\n";

s2.putdata();

return 0;

}

Output:

Parameterized Constructor with default argument

Parameterized Constructor with default argument

      Object 1 with both values

The two integers are... 10        20

The sum of the variables 10    + 20 = 30

      Object 2 with one value and one deafult value

The two integers are... 50        100

The sum of the variables 50    + 100 = 150


Illustration 14.24 to illustrate the significance of default constructor

#include<iostream>

using namespace std;

class simple

{

private:

int a, b;

public:

simple()      //default constructor

{

a= 0;

b= 0;

cout<< "\n default constructor"<<endl;

}

int getdata();

};

int simple :: getdata()

{

int tot;

cout<<"\nEnter two values ";

cin>>a>>b;

tot=a+b;

return tot;

}

int main()

{

int sum=0;

simple s1[3];

cout<<"\n\t\tObject 1 with both values \n";

for (int i=0;i<3;i++)

sum+=s1[i].getdata();

cout<<"\nsum of all object values is"<<sum;

return 0;

}

Output:

default constructor

default constructor

default constructor

      Object 1 with both values

Enter two values 10 20

Enter two values 30 40

Enter two values 50 50

sum of all object values is200


Illustration14.25 to illustrate implicit call and explicit call

#include<iostream>

using namespace std;

class simple

{

private:

int a, b;

public:

simple(int m,int n)

{

a= m ;

b= n;

cout<< "\n Constructor of class-simple invoked for implicit and explicit call"<<endl;

}

void putdata()

{

cout<<"\nThe two integers are... "<<a<<'\t'<< b<<endl;

cout<<"\n The sum of the variables "<<a<<" + "<<b<<" = "<<a+b; }

};

int main()

{

simple s1(10,20);                  //implicit call

simple s2=simple(30,45);         //explicit call

cout<<"\n\t\tObject 1\n";

s1.putdata();

s2.putdata();

return 0;

}

Explicit call to constructor creates a temporary instance

Output:

Constructor of class-simple invoked for implicit and explicit call

Constructor of class-simple invoked for implicit and explicit call

Object 1 

The two integers are... 10 20

The sum of the variables 10 + 20 = 30

Object 2 

The two integers are... 30 45

The sum of the variables 30 + 45 = 75


Illustration 14.26 to illustrate Copy constructor

#include <iostream>

using namespace std;

class Test

{

private:

int X;

int Y;

public:

      Test (int , int );         //parameterized constructor declaration

      Test (Test &); //Declaration of copy constructor to initialize data members.

void    Display();

};//End of class

Test:: Test(int a, int b)   //Definition of parameterized constructor.

{

      X = a;

      Y = b;

}

Test::Test(Test &T)      //Definition of copy constructor.

{

      X = T.X;

      Y = T.Y;

}

void Test:: Display()//Definition of Display () member function.

{

cout<<endl<< "X: " << X;

cout<<endl<< "Y: " << Y <<endl;

}

int main()

{

      Test T1(10,20) ; //Parameterized Constructor automatically called when

      //object is created.

      cout<<endl<<"T1 Object: " <<endl;

      cout<< "Value after initialization : " ;

      T1.Display();

      Test T2(T1);//Intialize object with other object using copy constructor cout<<endl<< "T2 Object: " <<endl;

      cout<< "Value after initialization : ";

      T2.Display();

      return 0;

}

Output:

T1 Object:

Value after initialization :

X: 10

Y: 20

T2 Object:

Value after initialization :

X: 10

Y: 20


Illustration14.27 to illustrate order of execution of constructor

#include<iostream>

using namespace std;

class outer

{

      int data;

      public:

      outer()

      {

      cout<<"\nconstructor of class outer ";

      }

};

class inner

{

      outer ot;                 // object ot of class outer is declared in class inner

      public:

      inner()

      {

      cout<<"\n constructor of class inner ";}

};

int main()

{

      inner in;

      return 0;

}

Output:

constructor of class outer

constructor of class inner


Illustration14.28 to illustrate dynamic initialization

#include<iostream>

using namespace std;

class X

{

int n;

float avg;

public:

      X(int p,float q)

      {

      n=p;

      avg=q;

      }

void disp()

{

      cout<<"\n Roll numbe:- " <<n;

      cout<<"\nAverage :- "<<avg;

}

};

int main()

{

      int a ; float b:

cout<<"\nEnter the Roll Number";

      cin>>a;

      cout<<"\nEnter the Average";

      cin>>b;

      X x(a,b);               // dynamic initialization

      x.disp();

      return 0;

}

Output:

Enter the Roll Number 1201

Enter the Average 98.6

Roll numbe:- 1201

Average :- 98.6


Illustration14.29 to illustrate destructor function in a class

#include<iostream>

using namespace std;

class simple

{

private:

int a, b;

public:

simple()

{

a= 0 ;

b= 0;

cout<< "\n Constructor of class-simple ";

}

void getdata()

{

cout<<"\n Enter values for a and b (sample data 6 and 7)... ";

cin>>a>>b;

}

void putdata()

{

cout<<"\nThe two integers are .. "<<a<<'\t'<< b<<endl;

cout<<"\n The sum of the variables "<<a<<" + "<<b<<" = "<<a+b;

}

~simple()

{ cout<<”\n Destructor is executed to destroy the object”;} };

int main()

{

simple s;

s.getdata();

s.putdata();

return 0;

}

Output:

Constructor of class-simple

Enter values for a and b (sample data 6 and 7)... 6 7

The two integers are .. 6       7

The sum of the variables 6 + 7 = 13

Destructor is executed to destroy the object


Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail
11th Computer Science : Chapter 14 : Classes and objects : Example C++ Programs: Classes and objects |

Related Topics

11th Computer Science : Chapter 14 : Classes and objects


Privacy Policy, Terms and Conditions, DMCA Policy and Compliant

Copyright © 2018-2024 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.