Unit - 1
Object Oriented Concepts
Q1) Explain object oriented technology? What are its advantages?
A1)
- Program is divided into number of objects.
- Objects are considered as real life entities that contain data and functions.
- Data is given more importance than functions.
- Data is not accessible to functions of other classes and hence data security is ensured.
- It employs bottom up approach.
Fig. Structure of Object Oriented Programming
Fig shows how objects can communicate with other objects with the help of functions. Here data is not accessible to external functions which ensure data security.
Advantages of OOP
- Real world complex problems can be modelled very well using OOP as OOP consists of object that represents real life entity.
- Using Inheritance class can reuse code of another class. This leads to faster software development and saves coding efforts and time.
- OOP ensures data security by making members of class private. Private members are accessible to same class hence data is not invaded by external functions.
- We can perform variety of tasks with the help of single function or operator by function or operator overloading.
- OOP provides better software development productivity than traditional programming languages due to data hiding, inheritance, polymorphism and templates.
Q2) Write Difference between POP and OOP.
A2)
Difference between POP and OOP
Sr. No. | Key | OOP | POP |
1. | Definition | Stands for Object Oriented Programming | Stands for Procedural Oriented Programming |
2. | Division | A program is divided to objects and their interactions. | A program is divided into functions and they interacts. |
3. | Approach | Follows bottom up approach | Follows top down approach |
4. | Data Hiding | Encapsulation is used to hide data. | Data is globally accessible. No data hiding present. |
5. | Inheritance supported | Supported | Not supported |
6. | Access control | Access control is supported via access modifiers. | No access modifiers are supported |
7. | Example | C++ | C |
Q3) What are tokens?
A3)
A token is the smallest element of a C++ program that is meaningful to the compiler. The C++ parser recognizes these kinds of tokens:
- Keywords
- Identifiers
- Numeric, Boolean and Pointer Literals
- String and Character Literals
- User-Defined Literals
- Operators
- Punctuators
Q4) Explain keyword and identifiers?
A4)
Keywords:
- In programming language keywords are reserved word and performs specific task.
- The keyword cannot used as variable because these are directly referred by compiler and assigning new value to keyword is not allowed.
- C++ language have 32 keywords.
Auto double int struct
Break else long switch
Case enum register typedef
Char extern return union
Const float short unsigned
Continue for signed void
Default goto sizeof volatile
Do if static while
Identifiers
- Identifiers are used to name the variables, arrays and functions.
- These are the user defined.
- To constitute the name digits, letters and underscore is used. Underscore is used as first character.
- Identifiers should not be same as keyword.
- After declaration identifiers are allowed to use anywhere in the program.
- It should not consist of white space.
- Example - _ab5.
Q5) Explain the data types in C++?
A5)
The table below shows the fundamental data types, their meaning, and their sizes (in bytes):
Data TypeMeaningSize (in Bytes)
IntInteger2 or 4
FloatFloating-point4
DoubleDouble Floating-point8
CharCharacter1
Wchar_tWide Character2
BoolBoolean1
VoidEmpty0
1. Int
The int keyword is used to indicate integers.
Its size is usually 4 bytes. Meaning, it can store values from -2147483648 to 214748647.
For example,
Int salary = 85000;
2. float and double
Float and double are used to store floating-point numbers (decimals and exponentials).
The size of float is 4 bytes and the size of double is 8 bytes. Hence, double has two times the precision of float. To learn more, visit C++ float and double.
For example,
Float area = 64.74;
Double volume = 134.64534;
As mentioned above, these two data types are also used for exponentials. For example,
Double distance = 45E12 // 45E12 is equal to 45*10^12
3. Char
Keyword char is used for characters.
Its size is 1 byte.
Characters in C++ are enclosed inside single quotes ' '.
For example,
Char test = 'h';
Note: In C++, an integer value is stored in a char variable rather than the character itself. To learn more, visit C++ characters.
4. wchar_t
Wide character wchar_t is similar to the char data type, except its size is 2 bytes instead of 1.
It is used to represent characters that require more memory to represent them than a single char.
For example,
Wchar_t test = L'ם' // storing Hebrew character;
Q6) Explain data abstraction.
A6)
Data Abstraction
- Data Abstraction is a process of providing only the essential details to the outside world and hiding the internal details, i.e., representing only the essential details in the program.
- Data Abstraction is a programming technique that depends on the seperation of the interface and implementation details of the program.
- Let's take a real life example of AC, which can be turned ON or OFF, change the temperature, change the mode, and other external components such as fan, swing. But, we don't know the internal details of the AC, i.e., how it works internally. Thus, we can say that AC seperates the implementation details from the external interface.
- C++ provides a great level of abstraction. For example, pow() function is used to calculate the power of a number without knowing the algorithm the function follows.
In C++ program if we implement class with private and public members then it is an example of data abstraction.
Data Abstraction can be achieved in two ways:
- Abstraction using classes
- Abstraction in header files.
Fig: Data Abstraction
Abstraction using classes: An abstraction can be achieved using classes. A class is used to group all the data members and member functions into a single unit by using the access specifiers. A class has the responsibility to determine which data member is to be visible outside and which is not.
Abstraction in header files: An another type of abstraction is header file. For example, pow() function available is used to calculate the power of a number without actually knowing which algorithm function uses to calculate the power. Thus, we can say that header files hides all the implementation details from the user.
Q7) Write a program to calculate the power of a number.
A7)
- #include <iostream>
- #include<math.h>
- Using namespace std;
- Int main()
- {
- Int n = 4;
- Int power = 3;
- Int result = pow(n,power); // pow(n,power) is the power function
- Std::cout << "Cube of n is : " <<result<< std::endl;
- Return 0;
- }
Output:
Cube of n is : 64
In the above example, pow() function is used to calculate 4 raised to the power 3. The pow() function is present in the math.h header file in which all the implementation details of the pow() function is hidden.
Q8) What are the Advantages of Abstraction?
A8)
Advantages of Abstraction:
- Implementation details of the class are protected from the inadvertent user level errors.
- A programmer does not need to write the low level code.
- Data Abstraction avoids the code duplication, i.e., programmer does not have to undergo the same tasks every time to perform the similar operation.
- The main aim of the data abstraction is to reuse the code and the proper partitioning of the code across the classes.
- Internal implementation can be changed without affecting the user level code.
Q9) What are the advantage of OOPs over Procedure-oriented programming language?
A9)
Advantage of OOPs over Procedure-oriented programming language
- OOPs makes development and maintenance easier where as in Procedure-oriented programming language it is not easy to manage if code grows as project size grows.
- OOPs provide data hiding whereas in Procedure-oriented programming language a global data can be accessed from anywhere.
- OOPs provide ability to simulate real-world event much more effectively. We can provide the solution of real word problem if we are using the Object-Oriented Programming language.
Q10) Write structure of C++ program.
A10)
When we consider a C++ program, it can be defined as a collection of objects that communicate via invoking each other's methods. Let us now briefly look into what a class, object, methods, and instant variables mean.
Object − Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behaviors - wagging, barking, eating. An object is an instance of a class.
Class − A class can be defined as a template/blueprint that describes the behaviors/states that object of its type support.
Methods − A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed.
Instance Variables − Each object has its unique set of instance variables. An object's state is created by the values assigned to these instance variables.
C++ Program Structure
Let us look at a simple code that would print the words Hello World.
#include <iostream>
Using namespace std;
// main() is where program execution begins.
Int main() {
cout << "Hello World"; // prints Hello World
return 0;
}
Let us look at the various parts of the above program −
The C++ language defines several headers, which contain information that is either necessary or useful to your program. For this program, the header <iostream> is needed.
The line using namespace std; tells the compiler to use the std namespace. Namespaces are a relatively recent addition to C++.
The next line '// main() is where program execution begins.' is a single-line comment available in C++. Single-line comments begin with // and stop at the end of the line.
The line int main() is the main function where program execution begins.
The next line cout << "Hello World"; causes the message "Hello World" to be displayed on the screen.
The next line return 0; terminates main( )function and causes it to return the value 0 to the calling process.
Q11) Explain Input and output streams in C++.
A11)
The C++ standard libraries provide an extensive set of input/output capabilities which we will see in subsequent chapters. This chapter will discuss very basic and most common I/O operations required for C++ programming.
C++ I/O occurs in streams, which are sequences of bytes. If bytes flow from a device like a keyboard, a disk drive, or a network connection etc. to main memory, this is called input operation and if bytes flow from main memory to a device like a display screen, a printer, a disk drive, or a network connection, etc., this is called output operation.
I/O Library Header Files
There are following header files important to C++ programs −
Sr.No | Header File & Function and Description |
1 | <iostream> This file defines the cin, cout, cerr and clog objects, which correspond to the standard input stream, the standard output stream, the un-buffered standard error stream and the buffered standard error stream, respectively. |
2 | <iomanip> This file declares services useful for performing formatted I/O with so-called parameterized stream manipulators, such as setw and setprecision. |
3 | <fstream> This file declares services for user-controlled file processing. We will discuss about it in detail in File and Stream related chapter. |
The Standard Output Stream (cout)
The predefined object cout is an instance of ostream class. The cout object is said to be "connected to" the standard output device, which usually is the display screen. The cout is used in conjunction with the stream insertion operator, which is written as << which are two less than signs as shown in the following example.
#include <iostream>
Using namespace std;
Int main() {
char str[] = "Hello C++";
cout << "Value of str is : " << str << endl;
}
When the above code is compiled and executed, it produces the following result−
Value of str is : Hello C++
The C++ compiler also determines the data type of variable to be output and selects the appropriate stream insertion operator to display the value. The << operator is overloaded to output data items of built-in types integer, float, double, strings and pointer values.
The insertion operator << may be used more than once in a single statement as shown above and endl is used to add a new-line at the end of the line.
The Standard Input Stream (cin)
The predefined object cin is an instance of istream class. The cin object is said to be attached to the standard input device, which usually is the keyboard. The cin is used in conjunction with the stream extraction operator, which is written as >> which are two greater than signs as shown in the following example.
#include <iostream>
Using namespace std;
Int main() {
char name[50];
cout << "Please enter your name: ";
cin >> name;
cout << "Your name is: " << name << endl;
}
When the above code is compiled and executed, it will prompt you to enter a name. You enter a value and then hit enter to see the following result −
Please enter your name: cplusplus
Your name is: cplusplus
The C++ compiler also determines the data type of the entered value and selects the appropriate stream extraction operator to extract the value and store it in the given variables.
The stream extraction operator >> may be used more than once in a single statement. To request more than one datum you can use the following −
Cin >> name >> age;
This will be equivalent to the following two statements −
Cin >> name;
Cin >> age;
The Standard Error Stream (cerr)
The predefined object cerr is an instance of ostream class. The cerr object is said to be attached to the standard error device, which is also a display screen but the object cerr is un-buffered and each stream insertion to cerr causes its output to appear immediately.
The cerr is also used in conjunction with the stream insertion operator as shown in the following example.
#include <iostream>
Using namespace std;
Int main() {
char str[] = "Unable to read....";
cerr << "Error message : " << str << endl;
}
When the above code is compiled and executed, it produces the following result−
Error message : Unable to read....
The Standard Log Stream (clog)
The predefined object clog is an instance of ostream class. The clog object is said to be attached to the standard error device, which is also a display screen but the object clog is buffered. This means that each insertion to clog could cause its output to be held in a buffer until the buffer is filled or until the buffer is flushed.
The clog is also used in conjunction with the stream insertion operator as shown in the following example.
#include <iostream>
Using namespace std;
Int main() {
char str[] = "Unable to read....";
clog << "Error message : " << str << endl;
}
When the above code is compiled and executed, it produces the following result−
Error message : Unable to read....
You would not be able to see any difference in cout, cerr and clog with these small examples, but while writing and executing big programs the difference becomes obvious. So it is good practice to display error messages using cerr stream and while displaying other log messages then clog should be used.
Q12) What are the OOP Paradigms?
A12)
OOP Paradigms
- The major motivating factor in the invention of object-oriented approach is to remove some of the flaws encountered in the procedural approach.
- OOP treats data as a critical element in the program development and does not allow it to flow freely around the systems.
- It ties data more closely to the functions that operate on it, and protects it from accidental modification from outside functions.
- OOP allows decomposition of a problem into a number of entities called objects and then builds data and functions around these objects.
- The data of an object can be accessed only by the function associated with that object.
- However, functions of one object can access the the functions of other objects.
Some of the striking features of object-oriented programming are
- Emphasis is on data rather than procedure.
- Programs are divided into what are known as objects.
- Data structures are designed such that they characterize the objects.
- Data is hidden and cannot be accessed by external functions.
- Objects may communicate with each other through functions.
- New data and functions can be easily added whenever necessary.
- Follows bottom-up approach in program design.
Q13) Write a program to accept and display details of book.
A13)
#include<iostream>//Step 1 Header file
Using namespace std ;
Class Book //Step 2 Declares class Book
{
Char name[10];//Declares data members name, pages and price.
Int pages; These data members are private.
Float price;
Public://Starts public section of class book
Void accept()//Step 3 Defines function “accept”
{//Entering the details of book
Cout<<“Enter name of book”;
Cin>>name;
Cout<<“Enter pages of book”;
Cin>>pages;
Cout<<“Enter price of book”;
Cin>>price;
}//End of accept function definition
Void display()//Step 4 Defines function display
{// Displays all the details of book
Cout<<“Name of book is :”<<name;
Cout<<“No. Of Pages in book are :”<<pages;
Cout<<“Price of book is:”<<price;
} // End of display function
};//Step 5 End of class
Int main()//Step 6 Start of main() function
{
Book b1,b2; //Step 7 Creates objects b1,b2
b1.accept();//Step 8 Calls accept function for b1
b2.accept();// Calls accept function for b2
b1.display();//Step 9 Calls display function for b1
b2.display();//Calls display function for b2
Return 0;
}// End of main
Q14) Give a short description on data encapsulation, data abstraction and information hiding, inheritance and polymorphism
A14)
Data encapsulation
- It encapsulates data and methods into object.
- Data wrapped in an object is not accessible to functions outside the class.
- Functions of same class can access data and hence this feature ensures data security.
Data abstraction and information hiding
- It hides detailed implementation of an object from user.
- It completely ignores low level details of how things works internally and represents only essential feature to hide complexity from user.
- For example, we know how to withdraw money from ATM but are unaware of internal processing that happens in ATM during withdrawal. This internal processing is hidden to avoid complexity.
Inheritance
- It is a mechanism of extending functionality from one class to another.
- Class can reuse the code of another class if they are tied together by inheritance.
- The original class is called as base/super/parent class and inherited class is called derived/sub/child class.
- Sub class inherits some or all the features of base class.
- Sub class adds its own features to base class so that it has combined features of both the classes.
- In this way it supports the concept of reusability.
- It can very well model hierarchical classification as shown below.
Fig: Inheritance
- Here Shape is considered as base class.
- Polygon and Ellipse are subclasses of class Shape.
- Rectangle and Hexagon are subclasses of Polygon so they inherit features of Polygon class.
- Similarly, Circle inherits features of Ellipse class.
Polymorphism
- It is ability to take more than one form depending upon the data types used in program.
- Consider the operation of finding area of any geometrical figure shown
- The operation “Area” is same but will take different forms depending upon type and number of arguments passed to “Area”.
- “Area” of square calculates area of square whereas “Area” of rectangle calculates area of rectangle.
- Though operation “Area” is same but it takes different forms depending upon type of geometrical figure.
Fig: Polymorphism
Q15) Write example of Data Encapsulation.
A15)
Any C++ program where you implement a class with public and private members is an example of data encapsulation and data abstraction. Consider the following example −
#include <iostream>
Using namespace std;
Class Adder {
public:
// constructor
Adder(int i = 0) {
total = i;
}
// interface to outside world
void addNum(int number) {
total += number;
}
// interface to outside world
int getTotal() {
return total;
};
private:
// hidden data from outside world
int total;
};
Int main() {
Adder a;
a.addNum(10);
a.addNum(20);
a.addNum(30);
cout << "Total " << a.getTotal() <<endl;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Total 60
Above class adds numbers together, and returns the sum. The public members addNum and getTotal are the interfaces to the outside world and a user needs to know them to use the class. The private member total is something that is hidden from the outside world, but is needed for the class to operate properly.