Showing posts with label Class 12. Show all posts

Class and Object in C++

Class and Object in C++

Object is the physical as well as logical entity where as class is the only logical entity.
Class: Class is a blue print which is containing only list of variables and method and no memory is allocated for them. A class is a group of objects that has common properties.
A class in C++ contains, following properties;
  • Data Member
  • Method
  • Constructor
  • Block
  • Class and Interface
Object: Object is a instance of class, object has state and behaviors.
An Object in C++ has three characteristics:
  • State
  • Behavior
  • Identity

Syntax

class_name object_reference;

Example

Employee e;
State: Represents data (value) of an object.
Behavior: Represents the behavior (functionality) of an object such as deposit, withdraw etc.
Identity: Object identity is typically implemented via a unique ID. The value of the ID is not visible to the external user. But,it is used internally by the JVM to identify each object uniquely.
Class is also can be used to achieve user defined data types.
In real world many examples of object and class like dog, cat, and cow are belong to animal's class. Each object has state and behaviors. For example a dog has state:- color, name, height, age as well as behaviors:- barking, eating, and sleeping.
Animal class

Vehicle class

Car, bike, truck these all are belongs to vehicle class. These Objects have also different different states and behaviors. For Example car has state - color, name, model, speed, Mileage. as we;; as behaviors - distance travel
Vehicle class

Difference between Class and Object in C++

ClassObject
1Class is a container which collection of variables and methods.object is a instance of class
2No memory is allocated at the time of declarationSufficient memory space will be allocated for all the variables of class at the time of declaration.
3One class definition should exist only once in the program.For one class multiple objects can be created.

Syntax to declare a Class

Syntax

 class Class_Name
  {  
    data member;  
    method;  
  }  

Simple Example of Object and Class

In this example, we have created a Employee class that have two data members eid and ename. We are creating the object of the Employee class and printing the objects value.

Example

#include<iostream.h>
#include<conio.h>

class Employee
{
public:
int salary  // data member
void sal()
{
  cout<<"Enter salary: ";
  cin>>salary;
  cout<<"Salary: "<<salary;
}
};
 void main()
 {
  clrscr();
  Employee e; //creating an object of Employee
  e.sal();
  getch();
 }  

Output

Enter salary: 4500 
Salary: 4500

Constructors And Destructors

Constructor in C++

Constructor is a special member method which will be called implicitly (automatically) whenever an object of class is created. In other words, it is a member function which initializes a class which is called automatically whenever a new instance of a class is created.

Features of Constructor

  • The same name as the class itself.
  • no return type.

Syntax

classname()
{
....
}
Note: If you do not specify a constructor, the compiler generates a default constructor for you (expects no parameters and has an empty body).

Why use constructor ?

The main use of constructor is placing user defined values in place of default values.

How Constructor eliminate default values ?

Constructor are mainly used for eliminate default values by user defined values, whenever we create an object of any class then its allocate memory for all the data members and initialize there default values. To eliminate these default values by user defined values we use constructor.

Example of Constructor in C++

#include<iostream.h>
#include<conio.h>

class sum
{
int a,b,c;
sum()
{
a=10;
b=20;
c=a+b;
cout<<"Sum: "<<c;
}
};

void main()
{
sum s;
getch();
}

Output

Sum: 30
In above example when we create an object of "Sum" class then constructor of this class call and initialize user defined value in a=10 and b=20. And here we no need to call sum() constructor.

Destructor

Destructor is a member function which deletes an object. A destructor function is called automatically when the object goes out of scope:

When destructor call

  • when program ends
  • when a block containing temporary variables ends
  • when a delete operator is called

Features of destructor

  • The same name as the class but is preceded by a tilde (~)
  • no arguments and return no values

Syntax

~classname()
{
......
}
Note: If you do not specify a destructor, the compiler generates a default destructor for you.

Example of Destructor in C++

#include<iostream.h>
#include<conio.h>

class sum
{
int a,b,c;
sum()
{
a=10;
b=20;
c=a+b;
cout<<"Sum: "<<c;
}
~sum()
{
cout<<<<endl;"call destructor";
}
delay(500);
};

void main()
{
sum s;
cout<<<<endl;"call main";
getch();
}

Output

Sum: 30
call main
call destructor
Explanation: In above example when you create object of class sum auto constructor of class is call and after that control goes inside main and finally before end of program destructor is call.

What is a copy constructor ?

A copy constructor is a special constructor in the C++ programming language for creating a new object as a copy of an existing object.

Example

class_name (const class_name&);
{
......
}
copy constructor

OOP concepts

Oops Concept in C++

The main purpose of C++ programming was to add object orientation to the C programming language, which is in itself one of the most powerful programming languages. If any programming language follow below oops concept then that language called object oriented programming language.
  • Object
  • Class
  • Encapsulation
  • Abstraction
  • Inheritance
  • Polymorphism
  • Modularity

Object

Object is the physical as well as logical entity where as class is the only logical entity.

Class

Class: Class is a blue print which is containing only list of variables and method and no memory is allocated for them. A class is a group of objects that has common properties.

Encapsulation (for more details click here

Encapsulation is a process of wrapping of data and methods in a single unit is called encapsulation. Encapsulation is achieved in C++ language by class concept. The main advantage of using of encapsulation is to secure the data from other methods, when we make a data private then these data only use within the class, but these data not accessible outside the class.

Abstraction (for more details click here

Abstraction is the concept of exposing only the required essential characteristics and behavior with respect to a context.
Hiding of data is known as data abstraction. In object oriented programming language this is implemented automatically while writing the code in the form of class and object.

Inheritance (for more details click here

The process of obtaining the data members and methods from one class to another class is known as inheritance. It is one of the fundamental features of object-oriented programming.

Polymorphism (for more details click here) 

The process of representing one Form in multiple forms is known as Polymorphism. Here one form represent original form or original method always resides in base class and multiple forms represents overridden method which resides in derived classes.
Modularity  (for more details click here
It is the property of a system that has been decompose into a set of cohesive and loosely coupled modules.
  1. It reduces complexity to some degree .
  2. It creates a number of well define,documented boundaries within a program.

Classes and Objects

Classes and Objects

C++ Class

  • Before you create an object in C++, you need to define a class.
  • A class is a blueprint for the object.
  • We can think of class as a sketch (prototype) of a house. It contains all the details about the floors, doors, windows etc. Based on these descriptions we build the house. House is the object.
  • As, many houses can be made from the same description, we can create many objects from a class.


How to define a class in C++?

  • A class is defined in C++ using keyword class followed by the name of class.
  • The body of class is defined inside the curly brackets and terminated by a semicolon at the end.

class className
   {
   // some data
   // some functions
   };

Example: Class in C++

class Test
{
    private:
        int data1;
        float data2;  

    public:  
        void function1()
        {   data1 = 2;  } 

        float function2()
        { 
            data2 = 3.5;
            return data2;
        }
   };
  • Here, we defined a class named Test.
  • This class has two data members: data1 and data2 and two member functions: function1() and function2().


Keywords: private and public

You may have noticed two keywords: private and public in the above example.
  • The private keyword makes data and functions private. Private data and functions can be accessed only from inside the same class.
  • The public keyword makes data and functions public. Public data and functions can be accessed out of the class.

Here, data1 and data2 are private members where as function1() and function2() are public members.
If you try to access private data from outside of the class, compiler throws error. This feature in OOP is known as data hiding.

C++ Objects

  • When 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.

Syntax to Define Object in C++

className objectVariableName;
  • You can create objects of Test class (defined in above example) as follows:


class Test
{
    private:
        int data1;
        float data2;  

    public:  
        void function1()
        {   data1 = 2;  } 

        float function2()
        { 
            data2 = 3.5;
            return data2;
        }
   };

int main()
{
    Test o1, o2;
}
Here, two objects o1 and o2 of Test class are created.
In the above class Testdata1 and data2 are data members and function1() and function2() are member functions.

How to access data member and member function in C++?

  • You can access the data members and member functions by using a . (dot) operator. For example,

o2.function1();
This will call the function1() function inside the Test class for objects o2.
Similarly, the data member can be accessed as:
o1.data2 = 5.5;
It is important to note that, the private members can be accessed only from inside the class.
So, you can use o2.function1(); from any function or class in the above example. However, the code o1.data2 = 5.5; should always be inside the class Test.

Example: Object and Class in C++ Programming

// Program to illustrate the working of objects and class in C++ Programming
#include <iostream.h>
#include<conio.h>

class Test
{
    private:
        int data1;
        float data2;

    public:
       
       void insertIntegerData(int d)
       {
          data1 = d;
          cout << "Number: " << data1;
        }

       float insertFloatData()
       {
           cout << "\nEnter data: ";
           cin >> data2;
           return data2;
        }
};

 int main()
 {
      Test o1, o2;
      float secondDataOfObject2;

      o1.insertIntegerData(12);
      secondDataOfObject2 = o2.insertFloatData();

      cout << "You entered " << secondDataOfObject2;
      return 0;
 }
Output
Number: 12
Enter data: 23.3
You entered 23.3
  • In this program, two data members data1 and data2 and two member functions insertIntegerData() and insertFloatData() are defined under Test class.

Two objects o1 and o2 of the same class are declared.
The insertIntegerData() function is called for the o1 object using:
o1.insertIntegerData(12);
  • This sets the value of data1 for object o1 to 12.

Then, the insertFloatData() function for object o2 is called and the return value from the function is stored in variable secondDataOfObject2 using:
secondDataOfObject2 = o2.insertFloatData();
In this program, data2 of o1 and data1 of o2 are not used and contains garbage value.

Stacks,Queues And Linked List

Stack
In computer science, a stack is a last in, first out (LIFO) data structure. A stack can is characterized by only two fundamental operations: push and pop. The push operation adds an item to the top of the stack. The pop operation removes an item from the top of the stack, and returns this value to the caller.
Stack using array
#include<iostream.h>
const int size = 5
class stack
{
int a[size];                    //array a can store maximum 5 item of type int of the stack
int top;                         //top will point to the last item pushed onto the stack
public:
stack( )                        //constructor to create an empty stack, top=-1 indicate that no item is
{top = -1 ;}     //present in the array

void push(int item)
{
If(top==size-1)
cout<<”stack is full, given item cannot be added”;
else
a[++top]=item;            //increment top by 1 then item at new position of the top in //the array a
}
int pop()
{
If (top==-1)
{
out<<”Stack is empty “;
return -1; //-1 indicates empty stack
}
else
       return a[top--];//return the item present at the top of the stack then decrement top by 1
}
            };
void main()
{
stack s1;
s1.push(3);
s1.push(5);
cout<<s1.pop()<<endl;
cout<<s1.pop()<<endl;
cout<<s1.pop();
}
Output is
5
3
Stack is empty -1

Linked list
In Computer Science, a linked list (or more clearly, "singly-linked list") is a data structure that consists of a sequence of nodes each of which contains data and a pointer which points (i.e., a link) to the next node in the sequence.



            Stack implementation using linked list
#include<iostream.h>
struct node
{
int item;                       //data that will be stored in each node
node * next;                //pointer which contains address of another node
};         //node is a self-referential structure which contains reference of another object type node
class stack
{
node *top;
public:
stack()              //constructor to create an empty stack by initializing top with NULL
{ top=NULL; }
void push(int item);
int pop();
~stack();
};
void stack::push(int item)                    //to insert a new node at the top of the stack
{
node *t=new node;                 //dynamic memory allocation for a new object of node type
if(t==NULL)
cout<<”Memory not available, stack is full”;
else
{
t->item = item;
t->next = top;              //newly created node will point to the last inserted node or NULL if
//stack is empty
top=t;                           //top will point to the newly created node
}
}

int stack::pop()            //to delete the last inserted node(which is currently pointed by the top)
{
if(top==NULL)
{
cout<<”Stack is empty \n”;
return 0;                       // 0 indicating that stack is empty
}
else
{
node *t=top;                //save the address of top in t
int r=top->item;           //store item of the node currently pointed by top
top=top->next;            // move top from last node to the second last node
delete t;                       //remove last node of the stack from memory
return r;
}
}

stack::~stack()                         //de-allocated all undeleted nodes of the stack when stack goes out of scope
{
node *t;
while(top!=NULL)
{
t=top;
top=top->next;
delete t;
}
};

void main()
{
stack s1;
s1.push(3);
s1.push(5);
s1.push(7);
cout<<s1.pop()<<endl;
cout<<s1.pop()<<endl;
cout<<s1.pop()<<endl;
cout<<s1.pop()<<endl;
}
Output is
7
5
3
Stack is empty 0
Application of stacks in infix expression to postfix expression conversion
Infix expression          operand1 operator operand2           for example     a+b
Postfix expression       operand1 operand2 operator           for example     ab+
Prefix expression         operator operand1 operand2           for example     +ab
Some example of infix expression and their corresponding postfix expression
Infix expression                                  postfix expression
a*(b-c)/e                                              abc-*e/
(a+b)*(c-d)/e                                       ab+cd-*e/
(a+b*c)/(d-e)+f                                   abc*+de-/f+


Algorithm to convert infix expression to postfix expression using stack:-
Suppose x is an infix expression and find postfix expression Y
1.      Push “(“  to the STACK, and add “)” to the end of X.
2.      Scan X from left to right and REPEAT Steps 3 to 6 for each element of X UNTIL the STACK is empty.
3.      If an operand is encountered, add it to Y.
4.      If a left parenthesis is encountered, push it on to STACK.
5.      If an operator is encountered then:
(a)    Repeatedly pop from STACK and add to Y each operator which has the same precedence as or higher precedence than operator.
(b)   Add operator to STACK.
6.        If a right parenthesis is encountered. Then:
(a)    Repeatedly pop from the STACK and add to Y each operator until a left parenthesis is encountered.
(b)   Remove the left parenthesis.  
7.       End
For example convert the infix expression (A+B)*(C-D)/E into postfix expression showing stack status after every step.
Symbol scanned from infix
Stack status
Postfix expression

(

(
((

A
((
A
+
((+
A
B
((+
AB
)
(
AB+
*
(*
AB+
(
(*(
AB+
C
(*(
AB+C
-
(*(-
AB+C
D
(*(-
AB+CD
)
(*
AB+CD-
/
(/
AB+CD-*
E
(/
AB+CD-*E
)

AB+CD-*E/
Answer: Postfix expression of (A+B)*(C-D)/E is AB+CD-*E/


Evaluation of Postfix expression using Stack
Algorithm to evaluate a postfix expression P.
/*Reading of expression takes place from left to right*/
1.      Read the next element      //First element for the first time
2.      If element is an operator then push the element in the Stack
3.      If the element is an operator then
{
4.      Pop two operands from the stack                         //pop one operator in case of unary operator
5.      Evaluate the expression formed by the two operands and the operator
6.      Push the result of the expression in the stack.
}
7.       If no-more-elements then
      Pop the result
Else
     Go to step 1.
8.      End.
Example1: Evaluate the following postfix expression showing stack status after every step
8, 2, +, 5, 3, -, *, 4 /
token scanned from
postfix expression
Stack status after processing the scanned token
Operation performed

8
8
Push 8
2
8, 2
Push 2
+
10
Op2=pop() i.e 2
Op1=pop() i.e 8
Push(op1+op2) i.e. 8+2
5
10, 5
Push(5)
3
10, 5, 3
Push(3)
-
10, 2
Op2=pop() i.e. 3
Op1=pop() i.e. 5
Push(op1-op2) i.e. 5-3
*
20
Op2=pop() i.e. 2
Op1=pop() i.e. 10
Push(op1-op2) i.e. 10*2
4
20, 4
Push 4
/
5
Op2=pop() i.e. 4
Op1=pop() i.e. 20
Push(op1/op2) i.e. 20/4
NULL
Final result 5
Pop 5 and return 5

 Example2:Evaluate the following Boolean postfix expression showing stack status after every step
True, False, True, AND, OR, False, NOT, AND
token scanned from
postfix expression
Stack status after processing the scanned token
Operation performed

True
True
Push True
False
True, False
Push False
True
True, False, True
Push True
AND
True, False
Op2=pop() i.e. True
Op1=pop() i.e. False
Push(Op2 AND Op1) i.e. False ANDTrue=False
OR
True
Op2=pop() i.e. False
Op1=pop() i.e. True
Push(Op2 OR Op1) i.e. True OR False=True
False
True, False
Push False

NOT
True, True
Op1=pop() i.e. False
Push(NOT False) i.e. NOT False=True
AND
True
Op2=pop() i.e. True
Op1=pop() i.e. True
Push(Op2 AND Op1) i.e. True AND True=True
NULL
Final result True
Pop True and Return True



QUEUE

Queue is a linear data structure which follows First in First out (FIFO) rule in which a new item is added at the rear end and deletion of item is from the front end of the queue. In a FIFO data structure, the first
element added to the queue will be the first one to be removed. Linear Queue implementation using Array
#include<iostream.h>
const int size=5;                      // size of queue
class queue
{          int front , rear;
int a[size];
public:
queue()                        //Constructor to create an empty queue
{          front=0;          
rear=0;
}         

void addQ( )               // insertion in array queue
{          if(rear==size)
cout<<”queue is full<<endl;
else
a[rear++]=item;
}

int delQ( )                    // deletion from the array queue
{          if(front==rear)
{
cout<<”queue is empty”<<endl;
return 0;
}
else     
return a[front++];
}
};
void main()
{
queue q1;
q1.addQ(3);
q1.addQ(5) ;
q1.addQ(7) ;
cout<<q1.delQ()<<endl ;
cout<<q1.delQ()<<endl ;
cout<<q1.delQ()<<endl;
cout<<q1.delQ()<<endl;
}
Output is
3
5
7
Queue is empty 0



Queue using linked list

#include<iostream.h>
struct node
{          int item;
node *next;
};
class queue
{          node *front, *rear;
public:
queue( )                                   // constructor to create empty queue
{          front=NULL;
rear=NULL;
}
void addQ(int item);
int delQ();
};
void queue::addQ(int item)
{          node * t=new node;
t->item=item;
t->next=NULL;
if (rear==NULL)         //if the queue is empty
{          rear=t;
front=t;            //rear and front both will point to the first node
}
else
{          rear->next=t;
rear=t;
}
}
int queue::delQ()
{          if(front==NULL)
cout<<”queue is empty”<<return 0;
else
{          node *t=front;
int r=t->item;
front=front->next; //move front to the next node of the queue
if(front==NULL)
rear==NULL;
delete t;
return r;
}
}
void main()
{          queue q1;
q1.addQ(3);
q1.addQ(5) ;
q1.addQ(7) ;
cout<<q1.delQ()<<endl ;
cout<<q1.delQ()<<endl ;
cout<<q1.delQ()<<endl;
cout<<q1.delQ()<<endl;
}
2,3 & 4 Marks Practice Questions
1. Convert the following infix expressions to postfix expressions using stack                                              2
(i)      A + (B * C) ^ D – (E / F – G)
(ii)    A * B / C * D ^ E * G / H
(iii)  ((A*B)-((C_D)*E/F)*G

2. Evaluate the following postfix expression E given below; show the contents of the stack during the evaluation
(i)      E= 5,9,+2,/,4,1,1,3,_,*,+ 2
(ii)    E= 80,35,20,-,25,5,+,-,*
(iii)  E= 30,5,2,^,12,6,/,+,-
(iv)  E=15, 3, 2, +, /, 7, + 2, *

3. An array A[40][10] is stored in the memory along the column with each element occupying 4 bytes. Find out the address of the location A[3][6] if the location A[30][10] is stored at the address 9000.                               3

4.  Define functions in C++ to perform a PUSH and POP operation in a dynamically allocated stack considering the following :                                                                                                                               4
struct Node
{
int X,Y;
Node *Link;
};
class STACK
{
Node * Top;
public:
STACK( )
{ TOP=NULL;}
void PUSH( );
void POP( );
~STACK( );
};

5. Write a function in C++ to perform a Add and Delete operation in a dynamically allocated Queue considering
     the following:                                                                                                                                             4
struct node
{
int empno ;
char name[20] ;
float sal ;
Node *Link;
};