Oop Ioe Notes Chapter Wise
Oop Ioe Notes Chapter Wise
Characteristics of POP
1. Emphasis is on algorithms
2. Follows top to bottom approach
3. Coding of large program is done by dividing it into smaller modules called functions
4. Global data can be shared by any functions
5. Functions are capable of transferring data from one form to another
Limitations of POP
1. Functions are emphasized rather than data.
2. Global data are vulnerable to an inadvertent change by a functions
3. Difficulty in recognizing which function uses which global data
4. Modification in global data also requires modification in functions using it
5. Function are action oriented so can not correspond to elements of the problem. So, it does not model the real world
problems.
Basic OOP
- In other to solve the limitations of the POP, the concept of OOP arises.
- In OOP, emphasis is given to data because of which data are protected from being accidental modification or data
corruption.
- Large problem is divided into objects and then build data and function around them.
Features of OOP
1. Emphasis is given on data rather than procedures.
2. Programs are divided into objects.
3. Function and data are tied together in a single unit.
4. Data can be hidden to prevent from accidental alteration from other functions.
5. Data access is done through the visible function.
6. Objects can communicate with each other through functions.
7. Follows bottom up approach.
1. Object:
- Objects are the basic run time entities in an object oriented system.
- They represent any item that the program can handle.
- The objects are so chosen to match with the real world objects.
- When a program is executed, the objects interact by sending messages to one another.
- Eg: Consider an object ‘student’ with data (name, roll, mark) and functions {total(), average(), display()}
2. Class:
- Class is the user defined data type used to declare the object.
- It is possible to declare any number of objects belonging to that class.
- Each object of a class is associated with the data of that class.
- Eg: To create an object mango belonging to the class fruit;
fruit mango;
3. Abstraction:
- Abstraction is the act of representing the essential features without including the background details or explanations.
- Classes are the concept of abstraction. So, class is a abstract data type.
- It can manage the program complexity.
4. Encapsulation:
- Encapsulation is the mechanism of combining data function together into a single unit.
- It prevents the data being accessed by other code.
5. Inheritance:
- Inheritance is the process of creating new classes based on the existing class such that new class acquires features from the
existing class and adds more features on it.
- The process of deriving a new class from the existing base class is called inheritance.
6. Polymorphism:
- Polymorphism is the ability to take more than one form depending on what they are operating on.
- It allows different objects to respond to the same operation in different ways, the response being specific to the type of
object.
- Eg: operator overloading, function overloading and so on.
Example of Some Object Oriented Languages
1. Small talk
2. Eiffel
3. JAVA
4. C#
5. D
6. C++
Advantages of OOP
1. Data hiding ensures program security.
2. Software development becomes easy as programs are divided into objects.
3. Proper management of software complexity.
4. Ensure real world problems modeling.
5. Easy to reuse codes.
6. Techniques like inheritance and templates eliminates redundant code.
Disadvantages of OOP
1. Requires more compilation time.
2. Difficult to trace and debug errors in complex program.
3. No benefits in short run of programs.
2. Introduction to C++
Need of C++
- It is very difficult to apply structured programming language like C to solve the complex problem and model the real world
problems perfectly.
- To overcome such complexity, the programmers find the need of C++ and then C++ was developed.
Features of C++
1. Namespace
It is used for logical grouping of program elements. It helps to develop large application by different members of the team
independently without conflict of identifiers name.
2. Class
It is user defined data types that combines data and function together.
3. Derived class
It is new class formed from existing classes which ensures code reuasbility.
4. Access controller
Private, public and protected keywords control the access of members within the class.
7. Reference variable
It is useful to pass arguments by reference.
8. Function Overloading
When same function name is used for different operation, it is called function overloading. It is used to manipulate same
nature of problems but with different numbers of arguments.
9. Default argument
Default argument come into action when no any arguments are passed during a function call.
C++ vs C
C C++
1. It was introduced by Dennis Ritchie at AT and T Bell lab.
1. It was introduced by Bjarne Stroupstup at AT and T Bell lab.
2. It follows procedural approach of programming
2. It follows object oriented approach.
paradigm.
3. Languages such as JAVA, object oriented PHP are influenced by C++.
3. Languages such as C++, perl, PHP are influenced by C.
4. C++ program is comparatively slower to compile.
4. C program is faster to compile.
5. It supports extension like operator overloading, inheritance and so on.
5. It does not support extension in programming.
6. It provides improved and extended libraries.
6. It provides fewer libraries.
7. It provides more keywords.
7. It provides fewer keywords.
History of C++
Example
Character Set
- Character set is the any acceptable alphabet, digit, symbol, etc that represent information in a program which together
forms tokens.
- The valid character set of C++ are:
1. Alphabets (a - z, A - Z)
2. Digits (0 - 9)
3. Special Symbols (+, -, *, /, =, {, }, etc)
4. White space (blank, new line, tab, etc)
Tokens
- Tokens are the smallest individual units of a program formed by the combination of character sets.
- The tokens in C++ are:
1. Keyword
2. Identifier
3. Constant
4. Operator
5. Punctuation
Keyword
- Keywords are the reserved words in C++ that have some special functioning.
- They can not be defined by user for any other purposes.
- They should be in lower case letters.
- Eg: int, auto, private, default, char, switch, if, for, etc.
Identifier
- Identifiers are the name of variables, function, array, class and so on created by the users.
- The rules for naming identifiers are as follows:
1. Only alphabets, digits and underscore are permitted.
2. Name can not start with digits.
3. Uppercase and lowercase letters are distinct.
4. Keywords can not be used.
5. No limits on the length of the name.
Constants / Literals
- Constants represent the fixed values that can not be altered during the program execution.
- It is classified as:
1. String constant
2. Numeric constant
3. Character constant
- Numeric constants are further divided into:
1. Integer
2. Float
3. Octal
4. Hex
Operator
- Operators are the special symbols used to perform mathematical or logical operations.
- The various operators used are as follows:
1. Arithmetic (+, -, *, /, %)
2. Assignment (=)
3. Self Assignment (++, --)
4. Arithmetic Assignment (+= , -=, *=, /=, %=)
5. Relational (>, <, >=, <=)
6. Equality (==, !=)
7. Logical (&&, ||, !)
8. Bitwise (>>, <<, ~, ^, |)
9. Other (?, :, ::, ( ), [ ], ->, etc)
Punctuator
- They are the special symbols which act as a punctuation marks.
- Eg: Parenthesis ( ), Braces { }, Comma ',', Semicolon :
- Variables are the entities that holds values which may alter during the program execution.
- Every variable must be declared.
Syntax:
data_type variable_name_1, variable_name_2, ..............., variable_name_n;
- Expressions are the combination of variable, constant, function call, operators and so on.
- Eg: x = a + b
Statement
- A statement carries out some action.
- Expression statement consists of any valid C++ expressions followed by a semicolon.
Eg: x = a + b;
- Compound statement is a group of C++ expression written wihin { and }.
Example:
{
a = b + c;
x = y;
}
- Control statement is used to control the flow of program under the given conditions.
Example:
if (a > b)
{
Data Type
- A data type defines a set of values that a variable can store and a set of operations that can be performed on that variable.
- It is of two types: Basic and Derived data types.
- Basic data types includes:
1. char
2. int
3. float, double
4. bool
- Derived data types includes:
1. array
2. structure
3. union
4. class
5. pointer
6. reference
- Type conversion is the process of conversion of one data type into another type.
- It is of two types:
1. Implicit conversion
2. Explicit conversion
Implicit Conversion
- While evaluating expression containing mixed data types, one data type is automatically converted to higher type.
- The basic rule is:
char --> short --> int --> long --> float --> double --> long double
Explicit Conversion
- It is done by programmers as per their needs.
- The basic syntax is:
(data_type) expression;
- Eg:
int x;
(float) x;``
Preprocessor Directives
Namespace
Syntax:
namespace namespace_name
{
//Declarations of variables, classes, functions
}
- In other to include the already defined namespace into our scope, keyword 'using' is added.
- Syntax : using namespace namespace_name
- The keyword 'const' added before variable declaration indicates that the variable value does not alter during program
execution.
Example:
const float pi = 3.17
const int max = 255
#include
int main()
{
char name[30];
int age;
cout << "Enter name and age:";
cin >> name >> age;
cout << "Name = " << name << "Age = " << age;
return 0;
}
Manipulators
- Manipulators are instruction to i/o stream that modify the output in various ways.
- The header file must be included to use manipulators.
endl Manipulator
- It causes a line feed to be inserted into the stream so that the subsequent text is displayed on new line.
- Eg: cout << "Subject : C++";
cout << endl << "Total :" << marks;
setw Manipulator
- It causes the number or string that follows it in the stream to be printed within a field specified in the argument.
- Syntax : cout << setw(n) << variable_name;
int main()
{
float mark1 = 99, mark2 = 74;
cout << setw(5) << "Names" << setw(7) << "Marks" << endl;
cout << setw(5) << "Suraj" << setw(7) << mark1 << endl;
cout << setw(5) << "Anil" << setw(7) << mark2 << endl;
return 0;
}
Output:
Names Marks
Suraj 99
Anil 74
New
- It obtains memory at run time from memory heap of operating system and returns the address of obtained memory.
- Syntax:
data_type *data_type_pointer;
data_type_pointer = new data_type; //Allocate for single variable
data_type_pointer = new data_type[size]; //Allocate an array
Delete
- It releases the memory allocated by 'new' back to operating system memory heap.
- Syntax:
delete data_type_ptr;
delete [ ] data_type_ptr;
int main()
{
int n, i, *arr, tot=0;
float avg;
cout << "How many numbers:";
cin >> n;
arr = new int[n];
cout << "Enter elements";
for (i = 0; i < n; i++)
{
cin >> arr[i];
tot += arr[i];
}
avg = tot / n;
cout << endl << "Total = " << tot;
cout << endl << "Average = " << avg;
delete []arr;
return 0;
}
1. Sequential
2. Selective (if, if_else, switch, ?:)
3. Repetitive (while, do_while, for)
Syntax:
if statement
if (test_exp)
statement;
if_else statement
if (test_exp)
statement1;
else
statement2;
nested if_else
if (exp1)
if (exp2)
statement 1;
else
statement 2;
else
statement3;
switch statement
switch (exp)
{
case val_1:
statement1;
break;
case val_2:
statement2;
break;
..........
..........
default:
default_statement;
}
Conditional operator
while loop
while (test_exp)
statement;
do_while loop
do
{
statement;
} while (test_exp);
for loop
Functions
Function Prototype
- A function header specified before function call.
- Syntax:
return_type function_name (parameter_list);
Function Definition
Syntax:
int main()
{
int p, t;
float r, i;
cout << "Enter the value for p, t and r :";
cin >> p >> t >> r;
i = calc(p, t, r); //Function call
cout << "The interest is : " << i;
return 0;
}
//Function Definition
float calc(int p, int t, float r)
{
return (p * t * r / 100);
}
Function Overloading
- It is a logical method of calling several functions with different arguments and data types which performs identical actions
by the same function name.
- Eg:
void display(); //No argument
void display(int); //one int argument
void display(int, char); //one int and one char argument
- The advantages of function overloading are as follows:
1. Eliminates the use of different function name for same operation.
2. Easy to understand and debug.
3. Easy to maintain code.
4. Better real world problem analysis.
- It is categorized as:
1. type of argument
2. number of argument
3. type and number of arguments
Type of Argument:
#include //Header Files
void display(char);
void display(int);
int main()
{
char ch = 's';
int num = 20;
cout << "Character : ";
display(ch);
cout << "Integer : ";
display(num);
return 0;
}
void display(char c)
{
cout << c;
}
void display(int n)
{
cout << n;
}
Number of Argument:
void display(int);
void display(int, int);
int main()
{
int ch = 10;
int num = 20;
cout << "One argument : ";
display(ch);
cout << "Two argument : ";
display(ch, num);
return 0;
}
void display(int c)
{
cout << c;
}
void display(int c, int n)
{
cout << c << n;
}
void display(int);
void display(char, int);
int main()
{
int ch = 's';
int num = 20;
cout << "One argument of integer type : ";
display(num);
cout << "Two argument of integer and character type: ";
display(ch, num);
return 0;
}
void display(int c)
{
cout << c;
}
Inline Function
- The function in which the code is copied in the called location is known as inline function.
- Syntax : inline return_type function_name (parameters)
- In ordinary function, when function is called, the control is passed to the calling function and after execution of the
function, the control is passed back to the called function.
- In case of inline function, on function call, the code of called function is copied at the place of the call and compiled at the
calling function without flow of control from calling to called function and back to calling function.
- This helps to minimize the execution time.
Default Argument
- During function call, less number of arguments can be passed than the actual number of arguments needed.
- This mechanism is possible by providing default argument.
- It helps in easy development and maintenance of the code.
int main()
{
display(); //Total = 30
display(30); //Total = 30 + 20 = 50
display(5, 5); //Total = 5 + 5 = 10
return 0;
}
Pass by Reference
- On passing arguments by reference, the formal arguments in called function became aliases to actual arguments in the
calling function.
- It is necessary when changes in called function is also important for the original arguments.
#include
int main()
{
int a = 4, b = 6;
cout << "Before swapping" << a << "and" << b;
swap(a, b);
cout << "After swapping" << a << "and" << b;
return 0;
}
Return by Reference
- A function is able to return a variable by reference.
#include
int main()
{
int a = 5, b = 10;
c = max(a, b);
cout << c;
return 0;
}
Array
- It is a collection of similar data items.
- Each data item is called an element.
- Index starts with 0.
- 1D array declaration : type array_name[no_of_element];
- 2D array declaration : type array_name[row] [column];
Pointer
- It is a variable containing address of another variable.
- It is useful to return more than one value from the called function.
- It creates complex data structures.
- It is declared as:
data_type *variable_name;
- Eg: int *pnum;
String
- It is an array of characters.
- It is terminated by null character.
- It is declared as:
char string_name[no_of_characters];
Structure
- It is the method of combining different data types.
- After defining a structure, a variable of its type can be declared.
Example:
struct sudent
{
char name[30];
int age;
};
student s1;
OR,
struct sudent
{
char name[30];
int age;
} s1;
Union
- It is similar to structure but differs in the way of storing and retrieving data.
- Union holds only one value for one data type.
- If a new assignment is done, the previous one is erased automatically.
Example:
Union name {
data_type mem1;
data_type mem2;
};
Enumeration
- Set of values represented by identifiers called enumeration constant.
Syntax:
enum name {
mem1;
mem2;
........
mem n;
};
Declaration:
enum name var1, var2, var3, ................ , varn;
class class_name
{
private:
data_type data1;
.........
public:
return_type function_name(data_type arg_list);
.............
};
Access Specifiers
- Once a class has been declared, it is possible to create variables of its type, known as objects of a class.
- Syntax : class_name obj_name1, obj_name2, .........;
- The necessary memory space is allocated when object is created.
- The public members of a class can be accessed by making use of member access operator or dot operator i.e '.'
- Syntax:
class_object . data_member;
class_object . member_function (actual_arguments);
- The member functions can be defined inside or outside the class definition.
#include
class employee
{
char name[30];
float salary;
public:
void getdata()
{
cout << "Enter name and salary : ";
cin >> name >> salary;
}
void showdata()
{
cout << name << salary << endl;
}
};
int main()
{
employee *eptr;
employee e;
eptr = &e;
class employee
{
char name[30];
float salary;
public:
void getdata();
void showdata();
};
int main()
{
employee *eptr;
employee e;
eptr = &e;
Constructors
Constructor
- Constructor is a special member function which is automatically called during object creation.
- Its name is same as the name of the class.
- It has no return value specification.
class counter
{
private:
int count;
public:
// Default Constructor
counter()
{
count = 0;
}
// Parameterized Constructor
counter(int n)
{
count = n;
}
.............
.............
};
int main()
{
counter c1;
counter c2(5);
}
Copy Constructor
- It declares and initializes an object from another object of its own class.
- When no copy constructor is defined, the compiler supplies its own copy constructor known as default constructor.
class code
{
int id;
public:
code() {} // Default constructor
code (int a) // Parameterized constructor
{
id = a;
}
code(code &a) //Copy constructor
{
id = a.id;
}
void display()
{
cout << id;
}
};
int main()
{
code a(100);
code b(a); //Calling copy constructor
code c = a; //Calling copy constructor
a.display();
b.display();
c.display();
return 0;
}
Destructors
- It is a member function whose name is same as the class name but is preceded by a tide (~).
- It is invoked when an object is destroyed.
- It never takes any argument nor any return value.
class test
{
private:
...........
public:
test() { } //Constructor
~test() { } //Destructor
};
#include
class complex
{
float real, img;
public:
void getdata()
{
cout << "Enter real and imaginary part";
cin >> real >> img;
}
void showdata()
{
cout << real << "+i" << img;
}
void add(complex c1, complex c2)
{
real = c1.real + c2.real;
img = c2.img + c2.img;
}
};
int main()
{
complex c1, c2, c3;
c1.getdata();
c2.getdata();
c3.add(c1, c2);
c1.showdata();
c2.showdata();
c3.showdata();
return 0;
}
#include
class complex
{
float real, img;
public:
void getdata()
{
cout << "Enter real and imaginary part";
cin >> real >> img;
}
void showdata()
{
cout << real << "+i" << img;
}
complex add(complex c2)
{
complex result;
result.real = real + c2.real;
result.img = img + c2.img;
return result;
}
};
int main()
{
complex c1, c2, c3;
c1.getdata();
c2.getdata();
c3 = c1.add(c2);
c1.showdata();
c2.showdata();
c3.showdata();
return 0;
}
Array of Objects
class employee
{
private:
int emp_id;
char name[30];
public:
void getdata();
void showdata();
};
class_name *pointer_to_object;
class_name object_name;
pointer_to_object = &object_name;
#include
class employee
{
char name[30];
float salary;
public:
void getdata()
{
cout << "Enter name and salary : ";
cin >> name >> salary;
}
void showdata()
{
cout << name << salary << endl;
}
};
int main()
{
employee *eptr;
employee e;
eptr = &e;
Syntax
class_name *obj_ptr;
obj_ptr = new class_name; //Dynamic allocation for object
obj_ptr = new class_name[size]; //Dynamic allocation for object array
class test
{
private:
int data;
...........
public:
test() { }
test(int a) { data = a; }
};
this Pointer
- Every non-static member function of object have access to 'this' pointer, which points to the object itself.
- It is defined implicitly.
- Any non-static function can find out the address of the object of which it is a member of.
Illustration of 'this' pointer
class counter
{
unsigned int count;
public:
counter()
{
count = 0;
}
counter(int n)
{
count = n;
}
counter operator ++()
{
++count;
return *this;
}
};
#include
class item
{
static int count; //Static Data Member Declaration
int number;
public:
void getdata(int a)
{
number = a;
count++;
}
void getcount()
{
cout << "Count = " << count;
}
};
int item :: count = 0; //Static Data Definition
int main()
{
item a, b;
a.getcount();
b.getcount();
a.getdata(100);
b.getdata(200);
a.getcount();
b.getcount();
return 0;
}
Output:
count = 0
count = 0
count = 2
count = 2
Static Function
- It belongs to a class not to any object.
- It can access only the static data members.
#include
class item
{
int code;
static int count;
public:
void setcode()
{
code = ++count * 10;
}
void showcode()
{
cout << code;
}
static void showcount() //Static Function Definition
{
count << count;
}
};
#include
class con
{
const int constdata; //Declaration of constant data member
public:
con() : constdata(0) {} //Definition of constant data through constructor
void display();
};
class time
{
private:
int hr, min, sec;
public:
time(int h = 0, int m = 0, int s = 0)
{
hr = h;
min = m;
sec = s;
}
int hour() const //Definition for constant functions
{
return hr;
}
int minute() const
{
return min;
}
int second() const
{
return sec;
}
};
Friend Function
- Using friend function, non-member of a class can access the member of a class.
- A friend function is not a member of any classes but has the full access to the member of class where it is declared as
friend.
- It can be invoked like a normal function without help of any object.
- It can not access member name directly and has to use an object name and dot operator with each member name.
- It takes object as arguments.
#include
class complex
{
private:
float real, img;
friend complex add(complex, complex); //Friend function declaration
public:
void getvalue()
{
cout << "Enter real and imaginary part : ";
cin >> real >> img;
}
void showvalue()
{
cout << real << " + i" << img;
}
};
int main()
{
complex c1, c2, c3;
c1.getvalue();
c2.getvalue();
c3 = add(c1, c2);
c3.showvalue();
return 0;
}
Friend Class
- Any function that is a member of another class can also be a friend of one class.
#include
class B;
class A
{
char passA[20];
public:
void getdata()
{
cout << "Enter password of A : ";
cin >> passA;
}
void showdata(B);
friend class B;
};
class B
{
char passB[20];
public:
void getdata()
{
cout << "Enter password of B : ";
cin >> passB;
}
void showdata(A a)
{
cout << "Password of A is : " << a.passA;
}
friend class A;
};
void A :: showdata(B b)
{
cout << "Password of B is : " << b.passB;
}
int main()
{
A a;
B b;
a.getdata();
b.getdata();
a.showdata(b);
b.showdata(a);
return 0;
}
5. Operator Overloading
Overridable Operators
- It is the mechanism of adding special meaning to an operator.
- It provides flexible option for extension of the meaning of the operator when applied to user defined data types.
- All operators are not overloadable.
- The operator that can be overloaded are as follows:
1. Member access operator (.)
2. Pointer to member access operator (.*)
3. Scope resolution operator (::)
4. Size of operator
5. Conditional operator (?:)
6. Runtime type information operator (typeid)
- All other operators can be overloaded.
- As a member function:
class class_name
{
//..................
public:
return_type operator operator_symbol(arg);
};
class class_name
{
//............
public:
friend return_type operator operator_symbol (arg, arg);
};
- The non-member operator function takes one more argument than the member operator function.
- For unary operator overloading, member function has no argument and non member function has one argument.
- For binary operator overloading, member function has one argument and non member function has two argument.
- After overloading, the meaning of operator can not be changed. So, use similar meaning only.
- The precedence, associativity and other syntactic characteristics of overloaded operator can not be changed.
- Use operator overloading only when necessary.
- Avoid ambiguity.
- New operators can not be created.
- Operator for basic types can not be created.
- It is overloaded with non-static member function with no argument or non-member function taking one argument.
- As a non-static member function:
class class_name
{
//...........
public:
return_type operator operator_symbol(); //Prefix operator
return_type operator operator_symbol(int); //Postfix operator
//..................
};
- As a non-member function:
#include
class counter
{
unsigned int count;
public:
counter() {count = 0;}
int ret_count()
{
return count;
}
void operator ++ ()
{
count++;
}
};
int main()
{
counter c1, c2;
cout << "c1 = " << c1.ret_count << "c2 = " << c2.ret_count;
++c1;
++c2;
++c2;
cout << "c1 = " << c1.ret_count << "c2 = " << c2.ret_count;
return 0;
}
#include
class counter
{
unsigned int count;
public:
counter() {count = 0;}
counter(unsigned int n) : count(n) {}
int ret_count()
{
return count;
}
counter operator ++ (int);
};
int main()
{
counter c1, c2;
cout << "c1 = " << c1.ret_count << "c2 = " << c2.ret_count;
c1++;
c2++;
c2++;
cout << "c1 = " << c1.ret_count << "c2 = " << c2.ret_count;
return 0;
}
- By non static member function taking one argument or a non member function taking two arguments.
Overloading + operator
#include
class complex
{
float real, imag;
public:
complex()
{
}
complex(float rel, float img)
{
real = rel;
imag = img;
}
void display()
{
cout << real << " + i" << imag;
}
complex operator + (complex c);
};
int main()
{
complex c1, c2, c3;
c1 = complex (4.4, 3.6);
c2 = complex (2.4, 3.5);
c3 = c1 + c2;
c3.display();
return 0;
}
Data Conversion
#include
class celcius
{
float temp;
public:
celcius() {}
celcius(float ftemp)
{
temp = (ftemp - 32) * 5 / 9;
}
void show()
{
cout << "Temp in celcius = " << temp;
}
};
int main()
{
celcius cel;
float fer;
cout << "Enter temp in fahrenheit : ";
cin >> fer;
cel = fer; // Basic to user defined
cel.showtemp();
return 0;
}
#include
class celcius
{
float temp;
public:
celcius() {
temp = 0;
}
void gettemp()
{
cout << "Temp in celcius = ";
cin >> temp;
}
operator float ()
{
float fer;
fer = (temp * 9 / 5) + 32;
return (fer);
}
};
int main()
{
celcius cel;
float fer;
cel.gettemp();
fer = cel;
cout << "Temp in Fahrenheit = " << fer;
return 0;
}
1. In Destination
class polar
{
private:
float radius, angle;
public:
polar() {}
polar(float rad, float ang)
{
radius = rad;
angle = ang;
}
float return_rad()
{
return radius;
}
float return_ang()
{
return angle;
}
void display()
{
cout << "(" << radius << "," << angle << ")";
}
};
class cartesian
{
private:
float x, y;
public:
cartesian()
{
x = 0;
y = 0;
}
cartesian(float x0, float y0)
{
x = x0;
y = y0;
}
cartesian(polar p)
{
x = p.return_rad() * cos(p.return_ang());
y = p.return_rad() * sin(p.return_ang());
}
void display()
{
cout << "(" << x << "," << y << ")";
}
};
int main()
{
polar pol(10.0, 0.7853);
cartesian cart;
cart = pol;
cart.display();
return 0;
}
2. In Source
class cartesian
{
private:
float x, y;
public:
cartesian()
{
x = 0;
y = 0;
}
cartesian(float x0, float y0)
{
x = x0;
y = y0;
}
void display()
{
cout << "(" << x << "," << y << ")";
}
};
class polar
{
private:
float radius, angle;
public:
polar() {
radius = 0;
angle = 0;
}
polar(float rad, float ang)
{
radius = rad;
angle = ang;
}
operator cartesian()
{
float x = static_cast (radius * cos(angle));
float y = static_cast (radius * sin(angle));
return cartesian(x, y);
}
void display()
{
cout << "(" << radius << "," << angle << ")";
}
};
int main()
{
polar pol(10.0, 0.7853);
cartesian cart;
cart = pol;
cart.display();
return 0;
}
Explicit Constructors
class test
{
int data;
public:
test()
{
data = 0;
}
explicit test(int n)
{
data = n;
}
};
// Called as:
test t1(2);
6. Inheritance
Base and Derived Class
Inheritance
- Inheritance is the process of organizing information in a hierarchical form.
- It helps in code reusability.
- Inheritance is the mechanism of code reusability by deriving a new class which can inherits all or some of the
characteristics of base class and also can add new features.
- The class which is used to derive new classes is called base class.
- The new classes derived from the existing class are called derived class.
- Base class is also known as ancestor, parent or super class.
-Derived class is also known as descendant, child or sub class.
- It causes a member to be visible by the member function and friend function of a class where it is declared.
- The protected members are visible to derived class members and friend of classes derived from base class.
- The purpose of making data member protected in a class is to make such members accessible to derived class function.
- Derived class inherits all features of its parent class and add its own features too.
- Syntax
- The process of creating members in the derived class with the same name as that of the visible members of base class is
called overriding.
- It is called overriding as the new name overrides or hides the old name inherited from base class.
Illustration of Overriding
#include
class base
{
protected:
int num;
public:
void read()
{
cout << "Enter number in base : ";
cin >> num;
}
void show()
{
cout << "The number in base is : " << num;
}
};
int main()
{
derived dl;
dl.read();
dl.show();
return 0;
}
Output:
-----------------
Enter number in derived : 5
The number in derived is : 5
Forms of Inheritance
Single Inheritance
- When a class is derived from only one base class, such derivation is called single inheritance.
Illustration:
#include
class student
{
private:
char name[30];
int id;
int age;
public:
void getdata()
{
cout << "Enter name, id and age : ";
cin >> name >> id >> age;
}
void show()
{
cout << name << id << age;
}
};
int main()
{
leader ld;
ld.getdata();
ld.show();
return 0;
}
Multiple Inheritance
- When a class is derived from two or more base class, it is called multiple inheritance.
Illustration:
#include
class school
{
private:
char school_name[30];
char address[40];
public:
void getdata()
{
cout << "Enter name of school and address : ";
cin >> school_name >> address;
}
void show()
{
cout << school_name << address;
}
};
class college
{
private:
char col_name[40];
long int phone;
public:
void getdata()
{
cout << "Enter name of college and phone number : ";
cin >> col_name, phone;
}
void show()
{
cout << col_name << phone;
}
};
int main()
{
student s1;
s1.getdata();
s1.show();
return 0;
}
#include
class company
{
private:
char company_name[30];
char address[40];
public:
void getdata()
{
cout << "Enter name of conpany and address : ";
cin >> company_name >> address;
}
void show()
{
cout << company_name << address;
}
};
int main()
{
manager m1;
m1.getdata();
m1.show();
return 0;
}
Hierarchical Inheritance
- When two or more classes are derived from single base class, it is called hierarchical inheritance.
Illustration:
#include
class employee
{
private:
char emp_name[40];
int id;
public:
void getdata()
{
cout << "Enter name of employee and id : ";
cin >> emp_name >> id;
}
void show()
{
cout << emp_name << id;
}
};
int main()
{
manager m1;
m1.getdata();
m1.show();
salesperson s1;
s1.getdata();
s1.show();
return 0;
}
Hybrid Inheritance
- When more than one form of inheritance are mixed, it is called hybrid inheritance.
- Creating a new derived class by multiple inheritance from base classes which are derived earlier from the same base class
is called multipath inheritance.
- In multipath inheritance shown in figure alongside, the classes B and C inherits the features of class A. The class D inherits
the same features from A through two paths B and C, causing ambiguity in accessing first base class A members.
- This ambiguity is eliminated by declaring base class as virtual while creating derived classes from the first base class.
Illustration of Multipath Inheritance
#include
class student
{
int roll;
char name[30];
public:
void getdata()
{
cout << "Enter name and roll number : ";
cin >> name >> roll;
}
void show()
{
cout << name << roll;
}
};
int main()
{
result r;
r.getdata();
r.show();
return 0;
}
Constructor Invocation
class base
{
public:
base()
{
cout << "From base class";
}
};
Output
---------------------------
From base class
class base
{
//Body of base class
};
int main()
{
derived d;
}
Output
--------------------------
From derived class
#include
class alpha
{
int x;
public:
alpha(int i)
{
x = i;
cout << "Alpha initialized";
}
void show()
{
cout << x;
}
};
class beta
{
int y
public:
beta(int j)
{
y = j;
cout << "Beta initialized";
}
void show_y()
{
cout << y;
}
};
int main()
{
gamma g(5, 10, 15, 20);
g.show();
g.show_y();
g.show_mn();
return 0;
}
Output
------------------------------
alpha initialized
beta initialized
gamma initialized
5
10
15 20
Destructors in Inheritance
- C++ allows a pointer in a base class to point to either a base class object or to any derived class object.
- Example:
B *bptr; //Pointer to base class
B b; //Base object
D d; //Derived object
bptr = &b; //bptr pointer points to base class object
bptr = &d; //bptr pointer points to derived class object
- Here, bptr can only access those members of D that are inherited from B but can not access the original members of D.
- For this, C++ permits the pointer declared as pointer to derived class.
#include
class base
{
public:
int b;
void show()
{
cout << b;
}
};
int main()
{
base *bptr;
base b;
bptr = &b;
bptr -> b = 100;
bptr -> show();
derived d;
bptr = &d;
bptr -> b = 200;
bptr -> show();
derived *dptr;
dptr = &d;
dptr -> d = 300;
dptr -> show();
return 0;
}
Output
-----------------------
b = 100
b= 200
b= 200
d = 300
Definition of Virtual Function
- A virtual function is one which does not really exist but it appears real in some parts of a program.
- The exact member function is selected at run time.
- The keyword 'virtual' is used for defining virtual function.
- It must be defined in public.
- The syntax is:
class class_name
{
pivate:
// ...............
public:
virtual return_type function_name(args)
{
........
}
};
- In case of hierarchical inheritance, the pointer to base class can access different functions belonging to different derived
classes using same object pointer with the help of array of pointers to base class using virtual function.
#include
class point
{
public:
virtual void draw()
{
cout << "point";
}
};
int main()
{
point pt;
line ln;
circle cr;
Output
-----------------------
point
line
circle
class class_name
{
//...........
public:
virtual return_type function_name() = 0;
};
class rectangle
{
protected:
float l, b;
public:
rectangle()
{
l = 0;
b = 0;
}
virtual float perimeter()
{
return (2*(l+b));
}
virtual float area() = 0;
};
}
square(float l, float b) : rectangle(l,b)
float area()
{
return l*b;
}
};
int main()
{
rectangle *bptr;
square sq(2,2);
bptr = &sq;
cout << "Perimeter = " << bptr -> perimeter();
cout << "Area = " << bptr -> area();
return 0;
}
Virtual Destructor
class derived
{
//...........
};
void main()
{
base *bptr = new derived;
delete bptr;
}
reinterpret_cast Operator
int ivar;
double dvar;
int *pivar;
double *pdvar;
void *pvoid;
pivar = reinterpret_cast (dvar)
pdvar = reinterpret_cast (ivar)
- It is the ability of finding object's type and changing their type at run time.
- It is provided by the use of dynamic_cast and typeid.
dynamic_cast operator:
- It performs run time cast along with verifying validity of the cast.
- If cast is invalid, then the cast fails.
- Syntax : dynamic_cast (expression);
- It is used to cast from base class pointer to derived class pointer.
- Example:
typeid operator:
- It returns reference to a standard library class type type_info defined in .
- The header file should be included.
- The syntax is:
typeid(expr);
Or,
typeid(type_name);
Missing chapters
9. Templates