Data Structures and Object Oriented Programming in C++: Unit-I
Data Structures and Object Oriented Programming in C++: Unit-I
Unit-I
PRINCIPLES OF OBJECT ORIENTED PROGRAMMING
Introduction
Tokens
Expressions
contour Structures
Functions in C++
Classes and Objects,
Constructors and destructors ,
Operators overloading
Type conversions.
1) Object :
Object is the basic unit of object-oriented programming. Objects are identified by its unique
name. An object represents a particular instance of a class. There can be more than one
instance of an object. Each instance of an object can hold its own relevant data. An Object is
a collection of data members and associated member functions also known as methods.
For example whenever a class name is created according to the class an object should be
created without creating object can’t able to use class. The class of Dog defines all possible
dogs by listing the characteristics and behaviors they can have; the object Lassie is one
particular dog, with particular versions of the characteristics. A Dog has fur; Lassie has
brown-and-white fur.
2) Class :
Classes are data types based on which objects are created. Objects with similar properties and
methods are grouped together to form a Class. Thus a Class represents a set of individual
objects. Characteristics of an object are represented in a class as Properties. The actions that
can be performed by objects become functions of the class and is referred to as Methods.
For example consider we have a Class of Cars under which Santro Xing, Alto and WaganR
represents individual Objects. In this context each Car Object will have its own, Model, Year
of Manufacture, Colour, Top Speed, Engine Power etc., which form Properties of the Car
class and the associated actions i.e., object functions like Start, Move, Stop form the Methods
of Car Class.No memory is allocated when a class is created. Memory is allocated only when
an object is created, i.e., when an instance of a class is created.
Data Abstraction increases the power of programming language by creating user defined data
types. Data Abstraction also represents the needed information in the program without
presenting the details. Abstraction refers to the act of representing essential features without
including the background details or explanation between them.
For example, a class Car would be made up of an Engine, Gearbox, Steering objects, and
many more components. To build the Car class, one does not need to know how the different
components work internally, but only how to interface with them, i.e., send messages to
them, receive messages from them, and perhaps make the different objects composing the
class interact with each other.
4) Inheritance :
Inheritance is the process of forming a new class from an existing class or base class. The
base class is also known as parent class or super class, the new class that is formed is called
derived class.
Derived class is also known as a child class or sub class. Inheritance helps in reducing the
overall code size of the program, which is an important concept in object-oriented
programming.
5) Polymorphism :
Polymorphism allows routines to use variables of different types at different times. An
operator or function can be given different meanings or functions. Polymorphism refers to a
single function or multi-functioning operator performing in different ways.
Poly a Greek term ability to take more than one form. Overloading is one type of
Polymorphism. It allows an object to have different meanings, depending on its context.
When an exiting operator or function begins to operate on new data type, or class, it is
understood to be overloaded.
6) Dynamic binding :
It contains a concept of Inheritance and Polymorphism.
7) Message Passing :
It refers to that establishing communication between one place to another.
OOPS ties data elements more closely to the functions that operates on.
Include files provides instructions to the compiler to link functions from the system
library.
Eg: #include <iostream.h>
#include – Preprocessor Directive
iostream.h – Header File
A class is a way to bind and its associated functions together. It is a user
defined datatype. It must be declared at class declaration part.
Member function definition describes how the class functions are implemented. This
must be the next part of the C++ program.
Finally main program part, which begins program execution.
main( )
{}
Program execution begins at the opening brace and ends at the closing brace. The closing
brace of the main function is the logical and of the program.
1.4. Input / Output statements
Input Stream
Syntax:
cin >> var1 >> var2 >>;
cin – Keyword, it is an object, predefined in C++ to correspond to the standard input
stream.
>> - is the extraction or get from operator
Extraction operation (>>) takes the value from the stream object on its left and places it in
the variable on its right.
Eg:
cin>>x;
cin>>a>>b>>c;
Output Stream:
Syntax:
cout<<var1<<var2;
It directs the contents of the variable on its right to the object on its left. Output stream can
be used to display messages on output screen.
Eg:
cout<<a<<b;
cout<<”value of x is”<<x;
cout<<”Value of x is”<<x<<”less than”<<y;
1.5. Tokens
The smallest individual units in a program are known as tokens. C++ has the following
tokens
♦ Keywords
♦ Identifiers
♦ Constants
♦ Strings
♦ Operators
1.5.1. Keywords
• It has a predefined meaning and cannot be changed by the user
• Keywords cannot be used as names for the program variables.
Keywords supported by C++ are:
1.6 Manipulators
Manipulators are operators used to format the data display. The commonly used
manipulators are endl, setw.
endl manipulators
It is used in output statement causes a line feed to be inserted, it has the same effect as using
the newline character “\n” in ‘C’ language.
#include <iostream.h>
main()
{
int a=10, b=20;
cout << “C++ language” << endl;
cout << “A value: “ << a << endl;
cout << “B value:” << b << endl;
}
setw Manipulator
The setw manipulator is used or specify the field width for printing, the content of the
variable.
Syntax: setw(width);
where width specifies the field width.
int a = 10;
cout << “ A value” << setw(5) << a << endl;
Output:
A value 10
Symbolic Constant
Symbolic constants are constants to which symbolic names are associated for the purpose of
readability and ease of handling.
• #define preprocessor directive
• const keyword
• enumerated data type
#define preprocessor directive
It associates a constant value to a symbol and is visible throughout the function in which it is
defined.
Syntax:
#define symbol name constant value
Eg
#define max_value 100
#define pi 3.14
The value of symbolic constant will not change throughout the program.
const keyword
Syntax:
const datatype var = constant;
E.g.:
const int max = 100;
main()
{
char x[max];
---------
---------
}
const size = 10;
Allowable statement, default symbolic constant type is integer. Here size is of type int.
Reference Variable:
A reference variable provides an alias (alternative name) for a previously defined
variable.
For example, if we make the variable sum a reference to the variable total, then
sum & total can be used interchangeably to represent that variable.
A reference variable is created as follows:
datatype & ref_name = var_name;
Eg:
float total = 100;
float & sum = total;
cout << sum << total;
Both the variables refer to the same data object in the memory i.e. total, sum 100
1.7. Type Conversion:
(i) Implicit type conversion
(ii) Explicit type conversion
Implicit type conversion
It will be done by the compiler, by following the rule of lower type converted to
higher type.
This process of splitting a large program into small manageable tasks and designing them
independently is called Modular Programming. A repeated group of instruction in a program
can be organized as a function. A function is a set of program statements that can be
processed independently.
Advantages
• Reduction in the amount of work and development time.
• Program and function debugging is easier.
• Reduction in size of the program due to code Reusability.
Function Components
• Function declaration or prototype
• Function Definition
• Function call
• Function parameters
• Function return statement
i. Function Prototype or Declaration:
It provides the following information to the compiler
• The name of the function
• The type of the value returned (optional, default is an integer)
• The number and type of the arguments that must be supplied in a call to the function.
• Syntax:
Return type function_name(argu1,argu2,……argun);
Return type - specifies the data type of the value in the return
statement.
Fun_name - name of the function.
Argu1,argu2…argun – type of argument to be passed from calling function to
the called function
• Examples:
int max(int,int);
It informs the compiler that the function max has 2 arguments of the type integer. The
function max() returns an integer values.
void max();
It informs the compiler that the function max has no arguments, max() is not returning
any value.
max();
It informs the compiler that the function max has no arguments.
The function max() returns an integer values.
In function prototype default return type is integer.
• The first line of the function definition is known as function declarator, and is
followed by the function body.
• The function delcarator and declaration must use the same function name, the number
of arguments, the arguments type and the return type.
• Function definition is allowed to write in a program either above or below the main ().
• If the function is defined before main (), then function declarator is optional.
• Example:
int max(int x, int y)
{
if(x>y)
return(x);
else
return(y);
}
For this function max() definition, it is declaration must be :
int max(int,int);
iii. Function call:
• A function, which gets life only when a call to the function is made.
• A function call specified by the function name followed by the arguments enclosed in
parenthesis and terminated by a semi colon.
• Syntax:
Function_name(argu1,argu2,……argun) ;
• If a function contains a return type the function call is of the following form:
var= Function_name(argu1,argu2,……argun) ;
• Example:
c=max(a,b);
iv. Function Parameters
• The parameters specified in the function call are known as actual parameters and
those specified in the function declarator (definition) are known as formal parameters
• For example in the main(), the statement c=max(a,b); passes the parameters(actual
parameters) a and b to max().
• The parameters x and y are formal parameters.
• When a function call is made, a one to one correspondence is established between the
actual and the formal parameters.
• The scope of the formal parameters is limited to its function only.
v. Function Return
• Functions can be grouped into two categories:
i. A Function does not have a return value (void function)
ii. Functions that have a return value.
The statements: return(x); and return(y);in function max() are called function return
statements. The caller must be able to receive the value returned by the function.
In the statement c=max(a,b) , The value returned by the function max() returning a value to
the caller.
Limitation of return
A key limitation of the return statement is that it can be used to return only one item from a
function.
Passing Data To Functions
The entity used to convey the message to a function is the function argument. It can be a
numeric constant, a variable, multiple variables, user defined data type, etc.
More than one object can be created with a single statement as,
Class student s1,s2,s3;
Or
Student s1,s2,s3.
Object can also be created by placing these names immediately after the closing brace.
Thus the definition
Class student
{
---------------
---------------
} s1,s2,s3;
protected:
... .
int age; // protected data
int getage( ): //protected function
... .
};
person p1; // Cannot access protected members
a = p1.age;
p1.getage( );
Public Members
All data members and function declared in the public section of the class can be accessed
without any restriction from anywhere in the program.
Eg:
class person
{
public:
int age; //public data
int getage( ); //public function
}
person p1;
a = p1.age; // can access public data
p1.getage( ); // can access public function
#include <iostream>
#include <iostream.h>
#include <conio.h>
class myclass {
int a,b;
public:
myclass(); // constructor
~myclass(); // destructor
void show();
};
myclass::myclass(){
cout << "In constructor\n";
a = 10;
b = 20;
}
void myclass::show()
{
cout << "A =" << a << endl << "B =" << b << endl;
cout << "Sum is " << a+b << endl;
}
void main()
{
clrscr();
myclass ob;
ob.show(); }
#include <iostream>
using namespace std;
class loc {
int longitude, latitude;
public:
loc() {}
loc(int lg, int lt) {
longitude = lg;
latitude = lt;
}
void show() {
cout << longitude << " ";
cout << latitude << "\n";
}
loc operator=(loc op2);
friend loc operator++(loc &op);
friend loc operator--(loc &op);
};
// Overload assignment for loc.
loc loc::operator=(loc op2) {
longitude = op2.longitude;
latitude = op2.latitude;
return *this; // i.e., return object that generated call
}
// Now a friend; use a reference parameter.
loc operator++(loc &op) {
op.longitude++;
op.latitude++;
return op;
}
// Make op-- a friend; use reference.
loc operator--(loc &op) {
op.longitude--;
op.latitude--;
return op;
}
int main()
{
loc ob1(10, 20), ob2;
ob1.show();
++ob1;
ob1.show(); // displays 11 21
ob2 = ++ob1;
ob2.show(); // displays 12 22
--ob2;
ob2.show(); // displays 11 21
return 0;
}
If we want to overload the postfix versions of the increment and decrement operators using a
friend, simply specify a second, dummy integer parameter. For example, this shows the
prototype for the friend, postfix version of the increment operator relative to loc.
// friend, postfix version of ++
friend loc operator++(loc &op, int x);
PART-A (2 MARKS)
1. Write any four features of OOPS.
2. What are the Basic concepts of OOS?
3. Define objects.
4. Define class.
5. Give any four advantages of OOPS.
6. Give any four applications of OOPS.
7. Give any four applications of c++.
8. Define tokens.
9. What is keyword?
10. Rules for naming the identifiers in C++.
11. What is a scope resolution operator?
12. What do you mean by enumerated data type?
13. What are symbolic constants?
14. What do you mean by dynamic initialization of variables?
15. What are reference variable?
16. Define constructor.
17. Define default constructor.
18. Define parameterized constructor.
19. Define default argument constructor.
20. What is the ambiguity between default constructor and default argument constructor?
21. Define copy constructor.
22. Define dynamic constructor.
23. Define const object.
24. Define destructor.
25. Define multiple constructors.
26. Write some special characteristics of constructor
27. Which operators cannot be overloaded?
28. What is meant by operator overloading?
-----------------------------------------------