Object Oriented Programming (Oop) Using C++: A Question Bank
Object Oriented Programming (Oop) Using C++: A Question Bank
PROGRAMMING (OOP)
USING C++
A QUESTION BANK
Chinmay D.Bhamare
2014
CHINMAY D BHAMARE,CHALISGAON
Its my first Object Oriented Programming (OOP)
language Question Bank. In this notes all types of
question are available related to c++. Most of the
questions are related to BCA syllabus.
So enjoy this notes and make your study easy
- chinmay D. Bhamare
(Smt.S.M.Agrrawal Inst.Of Mgt.,Chalisgaon)
Write Ans. Of Following Question .
What is class?
The class is one of the defining ideas of object-oriented programming. Among the important
ideas about classes are:
A class can have subclasses that can inherit all or some of the characteristics of the class. In
relation to each subclass, the class becomes the superclass.
Subclasses can also define their own methods and variables that are not part of their
superclass.
The structure of a class and its subclasses is called the class hierarchy.
Data Types ?
Boolean –bool
Character -char
Integer -int
Floating point- float
Double floating point- double
Valueless- void
Wide Character –wchar_t
What is Object ?
A class provides the blueprints for objects, so basically an object is created from a
class. We declare objects of a class with exactly the same sort of declaration that we
declare variables of basic types. Following statements declare two objects of class Box:
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
Types of Inheritance ?
Inheritance those are provided by C++ are as followings:
1. Single Inheritance
2. Multilevel Inheritance
3. Multiple Inheritance
4. Hierarchical Inheritance
5. Hybrid Inheritance
typedef struct {
double real;
double imag;
} complex;
doubles have been used for each field because their range is greater than floats and because the
majority of mathematical library functions deal with doubles by default.
In a similar way, structures could be used to hold the locations of points in multi-dimensional
space. Mathematicians and engineers might see a storage efficient implementation for sparse
arrays here.
Apart from holding data, structures can be used as members of other structures. Arrays of
structures are possible, and are a good way of storing lists of data with regular fields, such as
databases.
Another possibility is a structure whose fields include pointers to its own type. These can be used
to build chains (programmers call these linked lists), trees or other connected structures. These
are rather daunting to the new programmer, so we won't deal with them here.
Constructor’s name is identical to the Class name. Constructors can take parameters
but constructors have no return type. This is because; constructors return an object by
itself.
class Example
{
int x, y;
public:
Example();
Example(int a, int b);
//parameterized constructor
};
Example :: Example()
{
}
Example :: Example(int a, int b)
{
x = a;
y = b;
}
What Is Polymorphism ?
The word polymorphism means having many forms. Typically, polymorphism occurs
when there is a hierarchy of classes and they are related by inheritance.
C++ polymorphism means that a call to a member function will cause a different
function to be executed depending on the type of object that invokes the function.
cin>>variable;
cin>>variable1>>variable2;
This is called an input statement. In c++ , >> is called the stream extraction operator.
int feet;
int inches;
then input is
cin>>feet>>inches;
Output statements
In c++ output on standard output device is use cout and the operator << . The syntax
for output statement is
cout<< expression;
This is called an output statement. In C++ , << is called the stream insertion operator.
Syntax while and Do while Statement in c++ ?
While Loop:
while(condition)
{
statement(s);
}
Do While :
do
{
statement(s);
}while( condition );
What is encapsulation ?
Encapsulation is an Object Oriented Programming concept that binds together the data
and functions that manipulate the data, and that keeps both safe from outside
interference and misuse. Data encapsulation led to the important OOP concept of data
hiding
Data encapsulation is a mechanism of bundling the data, and the functions that use
them and data abstraction is a mechanism of exposing only the interfaces and hiding
the implementation details from the user.
C++ supports the properties of encapsulation and data hiding through the creation of
user-defined types, called classes. We already have studied that a class can
contain private, protected and publicmembers. By default, all items defined in a class
are private.
If you prefix new with the scope resolution operator (::), the global operator new() is
used. If you specify an argument_list, the overloaded newoperator that corresponds
to that argument_list is used. The type is an existing built-in or user-defined type.
A new_type is a type that has not already been defined and can include type specifiers
and declarators.
An allocation expression containing the new operator is used to find storage in free store
for the object being created. The new expression returns a pointer to the object created
and can be used to initialize the object. If the object is an array, a pointer to the initial
element is returned.
You can use set_new_handler() only to specify what new does when it fails.
You cannot use the new operator to allocate function types, void, or incomplete class
types because these are not object types. However, you can allocate pointers to
functions with the new operator. You cannot create a reference with the new operator.
When the object being created is an array, only the first dimension can be a general
expression. All subsequent dimensions must be constant integral expressions. The first
dimension can be a general expression even when an existing type is used. You can
create an array with zero bounds with the newoperator. For example:
Manipulator In c++ ?
Manipulators are functions specifically designed to be used in conjunction
with the insertion (<<) and extraction (>>) operators on stream objects, for
example:
cout << boolalpha;
They are still regular functions and can also be called as any other function using a
stream object as argument, for example:
boolalpha (cout);
Manipulators are used to change formatting parameters on streams and to insert or
extract certain special characters.
int main(void) {
int count = 0;
::count = 1; // set global count to 1
count = 2; // set local count to 2
return 0;
}
The declaration of count declared in the main() function hides the integer
named count declared in global namespace scope. The statement ::count =
1accesses the variable named count declared in global namespace scope.
You can also use the class scope operator to qualify class names or class member
names. If a class member name is hidden, you can use it by qualifying it with its class
name and the class scope operator.
Syntax Of Structure ?
struct structure _name
{
data_type member1;
data_type member2;
------------ --------------;
------------ --------------;
} ; //Semicolon is must & Before semicolon you can declare structure
What Is Syntax Of Inline Function ?
#include <iostream>
Class Syntax ?
class class_name {
access_specifier_1:
member1;
access_specifier_2:
member2;
...
} object_names;
Questions In Briefly :
Define Polymorphism Static & Dynamic
polymorphism?
The word polymorphism means having many forms. Typically, polymorphism occurs
when there is a hierarchy of classes and they are related by inheritance.
C++ polymorphism means that a call to a member function will cause a different
function to be executed depending on the type of object that invokes the function.
Static polymorphism refers to an entity existing in different physical forms simultaneously. Static
polymorphism involves binding of functions based on the number, type, and sequence of
arguments. The various types of parameters are specified in the function declaration, and
therefore the function can be bound to calls at compile time. This form of association is
called early binding. The term early binding stems from the fact that when the program is
executed, the calls are already bound to the appropriate functions.
The resolution of a function call is based on number, type, and sequence of arguments declared
for each form of the function. Consider the following function declaration:
When the add() function is invoked, the parameters passed to it will determine which version of
the function will be executed. This resolution is done at compile time.
Dynamic Polymorphism
Dynamic polymorphism refers to an entity changing its form depending on the circumstances. A
function is said to exhibit dynamic polymorphism when it exists in more than one form, and calls
to its various forms are resolved dynamically when the program is executed. The
term late binding refers to the resolution of the functions at run-time instead of compile time.
This feature increases the flexibility of the program by allowing the appropriate method to be
invoked, depending on the context.
Define Array? single And Multidimensional array ?
An array is a series of elements of the same type placed in contiguous
memory locations that can be individually referenced by adding an index to a
unique identifier.
That means that, for example, five values of type int can be declared as an
array without having to declare 5 different variables (each with its own
identifier). Instead, using an array, the five int values are stored in
contiguous memory locations, and all five can be accessed using the same
identifier, with the proper index.
For example, an array containing 5 integer values of
type int called foo could be represented as:
where each blank panel represents an element of the array. In this case,
these are values of type int. These elements are numbered from 0 to 4,
being 0 the first and 4 the last; In C++, the first element in an array is
always numbered with a zero (not a one), no matter its length.
Single Dimensional Array
The simplest form of the multidimensional array is the two-dimensional array. A two-
dimensional array is, in essence, a list of one-dimensional arrays. To declare a two-
dimensional integer array of size x,y, you would write something as follows:
type arrayName [ x ][ y ];
Where type can be any valid C++ data type and arrayName will be a valid C++
identifier.
A two-dimensional array can be think as a table, which will have x number of rows and y
number of columns. A 2-dimensional array a,
Multiple Inheritance is a feature of C++ where a class can inherit from more than one
classes.
The constructors of inherited classes are called in the same order in which they are
inherited.
To declare a function as a friend of a class, precede the function prototype in the class
definition with keyword friend as follows:
class Box
{
double width;
public:
double length;
friend void printWidth( Box box );
void setWidth( double wid );
};
To declare all member functions of class ClassTwo as friends of class ClassOne, place
a following declaration in the definition of class ClassOne:
A pure virtual function is a function that has the notation "= 0" in the
declaration of that function. Why we would want a pure virtual function and
what a pure virtual function looks like is explored in more detail below.
Here is a simple example of what a pure virtual function in C++ would look
like:
class SomeClass {
public:
virtual void pure_virtual() = 0; // a pure virtual function
// note that there is no function body
};
The "= 0" portion of a pure virtual function is also known as the pure
specifier, because it’s what makes a pure virtual function “pure”. Although
the pure specifier appended to the end of the virtual function definition may
look like the function is being assigned a value of 0, that is not true. The
notation "= 0" is just there to indicate that the virtual function is a pure
virtual function, and that the function has no body or definition. Also note
that we named the function “pure_virtual” – that was just to make the
example easier to understand, but it certainly does not mean that all pure
virtual functions must have that name since they can have any name they
want.
designed object oriented system objects never access shared or global data, they are
only permitted to use the data they have, or data they are given.
ifstream ifile;
ifile.open(“data2”);
Closing File
fout.close();
fin.close();
INPUT AND OUTPUT OPERATION
put() and get() function
the function put() writes a single character to the associated stream. Similarly, the function get()
reads a single character form the associated stream.
example :
file.get(ch);
file.put(ch);
write() and read() function
write() and read() functions write and read blocks of binary data.
example:
file.read((char *)&obj, sizeof(obj));
file.write((char *)&obj, sizeof(obj));
ERROR HANDLING FUNCTION
Finally, fstream, inherits both, the get and the put pointers, from iostream (which is itself derived
from both istream and ostream).
These internal stream pointers that point to the reading or writing locations within a stream can
be manipulated using the following member functions:
seekg() moves get pointer(input) to a specified location
file.seekg(-10, ios::cur);
Access Modifiers :- These are also Called as Access Visibility Controls means they
defined where a method and Data Member of class will be used either inside a class
,outside a class ,in inherited class or in main Method They Tells us the Scope of Methods
where they would be used Various types of Access Modifiers are as follows:-
Public Access: - Public Access modifiers Specifies that data Members and Member
Functions those are declared as public will be visible in entire class in which they are
defined. Public Modifier is used when we wants to use the method any where either in
the class or from outside the class. The Variables or methods those are declared as
public are accessed in any where , Means in any Class which is outside from our main
program or in the inherited class or in the class that is outside from our own class
where the method or variables are declared.
2) Protected Access:- The Methods those are declared as Protected Access modifiers
are Accessible to Only in the Sub Classes but not in the Main Program , This is the Most
important Access Modifiers which is used for Making a Data or Member Function as he
may only be Accessible to a Class which derives it but it doesn’t allows a user to Access
the data which is declared as outside from Program Means Methods those are Declared
as Protected are Never be Accessible to Another Class The Protected will be Accessible to
Only Sub Class and but not in your Main Program.
3) Private Access:- The Methods or variables those are declared as private Access
modifiers are not would be not Accessed outside from the class or in inherited Class or
the Subclass will not be able to use the Methods those are declared as Private they are
Visible only in same class where they are declared. By default all the Data Members and
Member Functions is Private, if we never specifies any Access Modifier in front of the
Member and Data Members Functions.
The signature of the declaration of a unary operator includes the operator token and the
type of parameter; it does not require the return type and the name of the parameter.
All the C# unary operators have predefined implementation that will be used by default
in an expression. These unary operators can be overloaded in user-defined types with
custom implementation by defining static member functions using the "operator"
keyword.
Unary Plus Operator (+): The result of an operation on a numeric type is the
value of the operand itself. This operator has been predefined for all numeric
types.
Unary Minus Operator (-): This operator can be used to negate numbers of the
integer, floating-point and decimal type.
Logical Complement (negation) Operator (!): This operator can be used only with
operands of Boole type.
Bitwise Complement (negation) Operator (~): This operator can be used with
integer, unit, long and ulong operand types. The result of the operation is a
bitwise complement (inverse of the binary representation) of the operand.
Prefix Increment (++) and Decrement (--) Operator: The operand can be a
variable, property access, or an indexer access. With an increment operator, the
result of the operation for operands of integer type would be the value
incremented by 1. With a decrement operator, the result would be the value
decremented by 1 from the operand. The increment/decrement operator can also
be used with postfix notation
Cast Operator: Used to build cast expressions for conversion to a given type.
This operator is represented by the symbol, "T," where T is the type to which the
operand or the result of the expression must be converted
Member functions of a nested class follow regular access rules and have no special
access privileges to members of their enclosing classes. Member functions of the
enclosing class have no special access to members of a nested class.
class A {
int x;
class B { };
class C {
int y;
void f(A* p, int i) {
void g(C* p) {
int main() { }
The compiler would not allow the declaration of object b because class A::B is private.
The compiler would not allow the statement p->x = i because A::xis private. The
compiler would not allow the statement int z = p->y because C::y is private.
You can define member functions and static data members of a nested class in
namespace scope. For example, in the following code fragment, you can access the
static members x and y and member functions f() and g() of the nested
class nested by using a qualified type name. Qualified type names allow you to define
a typedef to represent a qualified class name. You can then use the typedef with
the :: (scope resolution) operator to refer to a nested class or class member,
Union:
If we are having the less memory to use in our program, for example 64K,
we can use a single memory location for more than one variable this is
called union.
You can use the unios in the followig locations.
You can share a single memory location for a variable myVar1 and use the
same location for myVar2 of different data type when myVar1 is not required
any more.
You can use it if you want to user, for example, a long variable as two short
type variables.
When you dont know what type of data is to be passed to a function, and
you pass union which contains all the possible data types
1. union myUnion{
2. int var1;
3. long var2;
4. };
Structure:
5. struct Book
6. {
7. char Name[100];
8. char Author[100];
9. char Publisher[80];
10. int Year;
11. };
#include <iostream>
private:
double length;
};
Line::Line(void)
{
cout << "Object is being created" << endl;
}
Line::~Line(void)
{
cout << "Object is being deleted" << endl;
}
int main( )
{
Line line;
line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;
return 0;
}
We can define class members static using static keyword. When we declare a member
of a class as static it means no matter how many objects of the class are created, there
is only one copy of the static member.
A static member is shared by all objects of the class. All static data is initialized to zero
when the first object is created, if no other initialization is present. We can't put it in the
class definition but it can be initialized outside the class as done in the following
example by redeclaring the static variable, using the scope resolution operator :: to
identify which class it belongs to.
#include <iostream>
class Box
{
public:
static int objectCount;
// Constructor definition
Box(double l=2.0, double b=2.0, double h=2.0)
{
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;
// Increase every time object is created
objectCount++;
}
double Volume()
{
return length * breadth * height;
}
static int getCount()
{
return objectCount;
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
int main(void)
{
return 0;
}
Constructor:
Destructor:
Destructor is used to destroy the object that are created in memory previously.
Destructor can not take any arguments.
Destructor overloading can not be possible.
Destructor has same name as class name with tiled operator.
Syntax of Destructor:
class class_name
{
~class-name(void){}
};
Note on pointer ?
Pointers are variables that contain memory addresses (see Addresses,
Pointers, and References). They are an essential data type in C and C++,
and are used for the following:
Note on String ?
The string class is part of the C++ standard library. A string represents a sequence of characters.
#include <string>
The standard string class provides support for such objects with an interface similar to that
of standard containers, but adding features specifically designed to operate with strings of
characters.
The string class is an instantiation of the basic_string class template that uses char as the
character type, with its default char_traits and allocator types (see basic_string for more info on
thetemplate).
We should note the following features of an operator function for a binary operator:
It receives only one class type argument explicitly, in case of a member function. For a
friend function, two class types are received as arguments.
It returns a class type.
user_defined operator+(user_defined rhs)
{
user_defined temp;
temp.x = x + rhs.x;
temp.y = y + rhs.y;
return temp;
}
Application of C++?
It is a versatile language for handling very large programs
It is suitable for virtually any programming task including development of editors, compilers, databases,
communication systems and any complex real life application systems
It allows us to create hierarchy-related objects, so we can build special object-oriented libraries which can
be used later by many programmers
While C++ is able to map the real-world problem properly, the C part of C++ gives the language the ability
to get close to the machine – level details
C++ programs are easily maintainable and expandable
Features of OOPs ?
1. Programs are divided into objects
2. Data structures designed such that they characterize the objects.
3. Functions that operate on the data of an object are tied together in the data structure
4. Data is hidden and cannot be accessed by external functions
5. Objects may communicate with each other through functions
6. New data and functions can be easily added whenever necessary
7. IT follows bottom-up approach in program design
8. Concentration is on data rather than procedure
if statement
else if construct
switch statement
break statement
while loop
do while loop
for loop
Private
Private is the default access specifier for every declared data item in a class. Private
data belongs to the same class in which it is created and can only be used by the other
members of the same class.
Protected
When a data item is declared as protected it is only accessible by the derived class
member.
Public
Public allows to use the declared data item used by anyone from anywhere in the
program. Data items declared in public are open to all and can be accessed by anyone
willing to use their values and functions they provide.
Abstract classes are useful when creating hierarchies of classes that model
reality because they make it possible to specify an invariant level of functionality
in some methods, but leave the implementation of other methods until a specific
implementation of that class (a derived class) is needed.
Example :
class AB {
public:
virtual void f() = 0;
};
An abstract class has at least one abstract method. An abstract method will not
have any code in the base class; the code will be added in its derived classes.
The abstract method in the derived class should be implemented with the same
access modifier, number and type of argument, and with the same return type as
that of the base class. Objects of abstract class type cannot be created, because
the code to instantiate an object of the abstract class type will result in a
compilation error.
To understand pointer arithmetic, let us consider that ptr is an integer pointer which
points to the address 1000. Assuming 32-bit integers, let us perform the following
arithmatic operation on the pointer:
ptr++
#include <iostream>
int main ()
{
int var[MAX] = {10, 100, 200};
int *ptr;
Array of Object ?
C++ Class Objects are several types. They are array of objects, object classes, global objects and
local class objects,. In this section of C++ example programs, we are going to discuss about 3
source codes. These three C++ tutorial codes are specially designed for array of objects.
Beginners like students and professionals can use this sample CPP source code for free of cost.
#include<iostream.h>
#include<conio.h>
class c1 // Class definition
{
int m;
int n;
public: //Access specifiers
c1(int o, int p) // Constructor with 2 parameters
{
m=o;
n=p;
}
int getki()
{
return n;
}
int getih()
{
return m;
}
};
a Location object is to decide if it has the same screen coordinates as another Location object,
a Shape object is to decide if it has the same height and width as another Shape object, or
a File object is to copy itself to or from another File.
In each case the operation needs as its parameter an object in the same class as the one
containing the operation.
A second situation in which a class may refer to iself occurs when a method of a class returns an
instance of that class as a result. Some examples of methods that return objects in their own class
are the following:
a Shape object returns a new Shape object each of whose dimensions are some
percentage less or more than the size of the original Shape object,
a Location object returns a new Location object that is horizontally or vertically offset
from the original Location object, or
a File object returns a new File object that represents a temporary copy of itself.
In these examples the methods in the Shape, Location or File classes return another object in
their same class.
The File class is extended to add a method to perform the copying operations described above.
The extended definition is:
class File { // Version 2
private:
// encapsulated implementation goes here
public:
A const this pointer can by used only with const member functions. Data members
of the class will be constant within that function. The function is still able to change the
value, but requires a const_cast to do so:
Write A Programs :
Write a program to print even number.
#include <iostream>
using namespace std;
int main()
{
int count;
int x = 0;
while (x!=10)//(x!=12)
//I used 10 instead of 12 and it works fine but it
//needs to use 12 instead 10
{
x = x + 2;
cout << x << "\n""\n";
count++;
cout << endl;
}
return 0;
}
int main()
{
int x, y, temp;
temp = x;
x = y;
y = temp;
return 0;
}
int main()
int n = sizeof(arr)/sizeof(arr[0]);
print2Smallest(arr, n);
return 0;
int main()
{
int num1 = 0;
int num2 = 1;
int num_temp;
int num_next = 1;
int n;
cin >> n;
for (int i = 0; i < n; i++){
cout << num_next << " ";
num_next = num1 + num2;
num1 = num2;
num_temp = num2;
num2 = num_next - num1;
num1 = num_temp;
}
return 0;
}
#include <iostream>
using namespace std;
class A
{
public:
void display()
{
cout<<"Base class content.";
}
};
class B : public A
{
};
class C : public B
{
};
int main()
{
C c;
c.display();
return 0;
}
else{
cout<<"enter the first matrix"<<endl;
for(int i=0;i<l;i++){
for(int j=0;j<m;j++){
cin>>matrixA[i][j];
}
}
cout<<"enter the second matrix"<<endl;
for(int i=0;i<z;i++){
for(int j=0;j<n;j++){
cin>>matrixB[i][j];
}
}
for(int i=0;i<l;i++){
for(int j=0;j<n;j++){
matrixC[i][j]=0;
for(int k=0;k<m;k++){
matrixC[i][j]=matrixC[i][j]+(matrixA[i][k] * matrixB[k][j]);
}
}
}
void numberFunction(int i) {
cout << "The number is: " << i << endl;
}
int main() {
return 0;
}
#include<iostream.h>
#include<conio.h>
};
int main()
{
clrscr();
getch();
}
int main()
{
// Variable Declaration
int a;
#include<iostream.h>
#include<conio.h>
class copy
{
int var,fact;
public:
copy(int temp)
{
var = temp;
}
double calculate()
{
fact=1;
for(int i=1;i<=var;i++)
{
fact = fact * i;
}
return fact;
}
};
void main()
{
clrscr();
int n;
cout<<"\n\tEnter the Number : ";
cin>>n;
copy obj(n);
copy cpy=obj;
cout<<"\n\t"<<n<<" Factorial is:"<<obj.calculate();
cout<<"\n\t"<<n<<" Factorial is:"<<cpy.calculate();
getch();
}
#include <iostream>
Feedback :
Chinmayb07@hotmail.co.uk