C++ Notes
C++ Notes
of things to done such as reading, calculating and printing. A number of functions are
written to accomplish these task. Primary focus is on functions.
Global data
Accessible by any function
Function A Function B
1
Object A Object B
Data data
| |
functions functions
Object C
Functions
|
data
1. Object:- objects are the basic run time entities in object oriented
programming. They are variables of a class. Any number of objects can be
created. Each object is associated with the data type class with which they
are created. They may represent a person, a place, a bank account etc.
Object: student
Data
Name
Marks
Functions
Total
Percentage
2. Class :- The entire set of data and code of an object can be made as user
defined data type is known as a class. Class is a collection of objects of
similar type.
Eg. Fruits, students, employee etc.
2
overloading , function overloading are the examples of polymorphism. It is
used in implementing inheritance.
Ex.
Student.result(marks);
| | |
| | |
object message information
Tokens:- the smallest individual unit in C++ is called tokens. Tokens are
Keywords ,identifiers ,constants ,strings ,operators.
Keywords:-The keywords are the reserved identifiers & its meaning known to the
compiler . They can’t be used as names for the program variables.
Keywords are
int, break, continue etc.
Identifiers :- identifiers refers to the names of variables, functions, classes, arrays etc.
created by the programmer.
Rules for identifiers are
1. only alphabetic characters, digits and underscores are permitted.
2. The name can’t start with digits.
3. upper case and lower case letters are distinct.
4. keywords can’t be used as identifier name.
5. there is no limit on the characters of the identifier.
6. all characters in the name are significant.
Constants:- constants refers to the fixed values that do not change during program
execution. constants are
Integer constant
Eg. 56
Floating point constant
Eg 45.78
Character constant
Eg. ‘F’
String constant
Eg. “I know C++ programming language.”
4
Basic or built in data types:-The data types which are known to the compiler are
called built in data types.
Built in data types are
• Integer:- It accepts whole numbers only. It is denoted by int. Its takes 2 bytes to
store the number. It can be signed int , unsigned int.
Eg.
int a=23;
• Short integer:-It accepts whole numbers whose size is smaller then int. It takes 2
bytes to store the number. It can be short int, unsigned short int.
Eg.
short int s=1;
• Long int :- It accepts whole numbers whose size is bigger then int. It takes 4
bytes to store the number. It can be long int, unsigned long int.
Eg.
long int b=556789;
• Character:- It accepts a single character. It is denoted by char. It takes 1 byte to
store the number. It can be signed char, unsigned char
Eg.
char c=‘e’;
• Floating point:-It accepts fractional numbers. It is denoted by float. It takes 4 byte
to store the number.
Eg. float f=45.6;
• Double:-It accepts the fractional numbers larger then float. It takes 8 bytes to store
the number.
Eg. double d=2.4E+20;
• Long double:- It accepts the fractional numbers larger then double. It takes 10
bytes to store the number.
Eg. long double d=1.1E+4399;
User defined data types:-data types defined by the user as per program’s requirement
are called user defined data types.
User defined data types are
• Structure:- structure is a collection of variables of different data types. It is
denoted by keyword struct.
Eg.
struct
{
char name[20];
int rollno;
}
• Union:-Its members all occupy the same memory location. The size of the union
is the size of its largest member. It is defined by keyword union.
Eg.
Union student
{
5
int rollno;
double percentage;
}
• Class:- The entire set of data and code of an object can be made as user defined
data type is known as a class. Class is a collection of objects of similar type.
Eg. Fruits, students, employee etc.
• Enumerated data type:-in this data type names are associated to the numbers. It is
denoted by keyword enum.
Eg.
enum option{false,true};
option f; //f is option type
Control structures:- control structures are the method to trace the flow of execution
of statements. It makes the program debugging easy.
Control structures are
1. Sequence structure
2. Selection structure
3. Loop structure
1. Sequence structure:-the instructions are executed one after the other in the
sequence in which they are specified in the program.
6
Step1
|
step2
|
step3
|
II double alternative
if (condition)
{
Module A
}
Else
{
Module B
}
else if (condition3 )
{
Module C
}
else
{
Module D
}
while(condition)
{
Module B
}
do
{
Module C
}while(condition);
Manipulators:- manipulators are operators that are used to manipulate the data
display. Manipulators are endl and setw
endl:- when endl is used in an output statement , causes a linefeed to be inserted. It has
the same effect as using newline character “\n”.
eg.
cout<<”good morning India”<<endl;
setw:- setw is used to specify a field width for printing the value of a variable.
eg.
cout<<setw(5)<<sum;
8
Q3.1 What is a class. Give its general form and explain in brief.
Ans: class :- The entire set of data and code of an object can be made as user
defined data type is known as a class. Class is a collection of objects of similar
type.
General form of a class declaration is
class class_name
{
private:
variable declarations;
function declarations;
public:
variable declarations;
function declarations;
};
where
private, public are the visibility modes .
variables declared inside the class are known as the data members.
Functions declared inside the class are known as the member functions.
class student
{
int rollno;
int marks;
public:
void getdata( ); //function declaration
//member function definition inside the class
void putdata( )
{
cout<<”rollno:”<<rollno;
cout<<”\nmarks:”<<marks;
}
};
//member function definition outside the class
void student::getdata( )
{
9
cout<<”enter rollno and marks”;
cin>>rollno>>marks;
}
Q3.4 Can we use the same function name for a member function of a class and an
outside function in the same program file? If yes, how are they distinguished ?
If no, give reasons.
Ans: yes, we can use the same function name for a member function of a class and
an outside function in the same program file. A member function of a class is
accessed with help of its object. While the outside function is accessed as a
normal function without the help of an object. Its prototype is declared before
main( );
eg.
#include <iostream.h>
#include <conio.h>
void putdata();
class student
{
int rno;
int marks;
public:
void getdata()
{
cout<<"enter rno,marks";
cin>>rno>>marks;
}
void putdata()
{
cout<<rno<<endl;
cout<<marks;
}
};
10
void main()
{
student s;
s.getdata();
s.putdata();
putdata();
}
void putdata()
{
cout<<"rno"<<endl;
cout<<"marks";
}
Q3.5 What is a friend function? what are the characteristics of the friend function?
Ans: A function that is declared with the keyword friend is known as a friend
function. It is defined elsewhere in the program like a normal C++ function.
Characteristics of friend function
i) It is not in the scope of class to which it is declared as a friend.
ii) It has full access to the private and public members of the class.
iii) It can be invoked like a normal function without the help of any object.
iv) It has the objects as arguments
v) It can be declared in private or public part of the class.
vi) To access the members it has to use an object name and dot operator with each
member name.(eg. ob.x)
Q3.6 Describe the mechanism of accessing data members and member functions in
the following cases:
a. Inside the main program.
b. Inside a member function of same class.
c. Inside a member function of another class.
Ans: Accessing class members
a. inside the main function:-private members can’t be accessed inside the main
function. Public data members and member functions can be access by using an
object of the same class.
b. inside member function of the same class:-private and the public data member
and member function can be access directly by using the name of the member.
c. inside a member function of another class:-By making the member function of
one class as a friend function of another class private and public data member
and member functions can be accessed.
Q3.7 What is a friend function? What are the merits and demerits of using friend
functions.
Ans: A function that is declared with the keyword friend is known as a friend
function. It is defined elsewhere in the program like a normal C++ function.
Merits of friend function
i It has full access to the private and public members of the class.
ii It can be declared in private or public part of the class.
11
Demerits of friend function
i private data is available to friend function therefore data may not be secure.
ii It is not in the scope of class to which it is declared as a friend.
Q3.8 When do we declare a member of a class static ? what are the characteristics of
the static member?
Ans: Member of a class can be declared as static when the member is common to
the entire class. data members as well as member functions can be static.
Features of static data member
i It is initialized to zero when the first object of its class is created. No other
initialization is permitted.
ii Only one copy of that member is created for entire class and is shared by all
the objects of that class.
iii It is visible only within the class, but its lifetime is the entire progam.
Features of static member function
i A static function can have access to only other static members.
ii A static member function can be called using the class name.
x=m;
y=n;
}
};
void main( )
{
item ob1(10,20); //object 1 is created
item ob(30,40); //object2 is created
}
Q4.4 Can we have more then one constructors in a class? If yes, explain the need for
such a situation.
Ans:- Yes, we can have more then one constructor in a class. Such constructor is
called overloaded constructor.
Overloaded constructor is needed when more then one objects are created of
same class and the objects are with the different number of arguments.
Eg.
class item
{
int x,y;
public:
item ( ){ } //no argument constuctor
item(int c) //one argument constructor
13
{
x=c;
}
item(int m, int n) //two argument constructor
{
x=m;
y=n;
}
};
void main( )
{
item ob1; //no arg. Constructor is invoked
item ob2(10); //one arg. Constructor is invoked
item ob3(30,40); //two arg. Constructor is invoked
}
char *name;
int length;
name=new char[length+1];
in above example object ob2 is created and initialized with the value of object
ob1.
15
The general form of operator function is:
where
return type is the type of value returned by the specified operation.
op is the operator being overloaded.
operator is the keyword
operator op is the function name.
op-arglist is the list of arguments.
Eg.
Vector operator+(vector) // vector addtion
Q5.4 How many arguments are required in the definition of an overloaded unary
operator?
Ans:- When unary operator is overloaded by using operator function as a friend
function one argument is required.
Eg.
void friend operator-(sign); //sign is a class name
When unary operator is overloaded by using operator function as a member
function no argument is required. This is because the object used to invoke the
member function is passed implicitly and therefore available for the member
function.
Eg.
void operator-( ) //overload unary operator
Q5.5 Differentiate operator overloading using member function and friend function.
16
Ans:- operator overloading using operator overloading using
member function friend function
1. for unary operator overloading 1. for unary operator overloading
no explicit argument is required. One explicit argument is required.
2. for binary operator overloading 2. for unary operator overloading
one explicit argument is required. two explicit argument are
required.
3. member function can overload 3. friend function cannot overload
following operators following operators
= assignment operator = assignment operator
( ) function call operator ( ) function call operator
[ ] subscripting operator [ ] subscripting operator
-> class member operator -> class member operator
Q5.8 What are the different types of data type conversion are present ? Explain in
brief.
Ans:- Three types of data conversion between uncompatible types are
i) Conversion from basic type to class type
ii) Conversion from class type to basic type
iii) Conversion from one class type to another class type
i) Conversion from basic type to class type:- The constructors used for the type
conversion take a single argument whose type is to be converted.
Eg.
Class time
{
int hrs;
int min;
public:
time( ){ }
time(int t)
{
hrs=t/60;
min=t%60;
}
};
void main( )
{
time ob; //object is created
17
int t=65;
ob=t; // int to class type
}
class time
{
int hr;
int sec;
public:
time(){}
time(int h, int s)
{
hr=h;
sec=s;
}
operator int() //conversion function
{ //convert time to seconds
int s1=hr*60;
s1 +=sec;
return s1;
}
};
void main()
{ clrscr();
time t1(1,30); //calling 2 arg constructor
/*uses conversion function to convert time to
seconds*/
int s=t1;
cout<<"time in seconds="<<s;
getch();
}
iii) Conversion from one class type to another class type:-Conversion between
objects of different classes can be carried out by either a constructor or a
conversion function.
/*conversion between objects of different classes
converts polar to rec using routine in rec(destination)*/
#include<iostream.h>
#include <math.h>
#include<conio.h>
class polar
{
18
private:
double radius;
double angle;
public:
polar()
{
radius=0.0;
angle=0.0;
}
polar(double r,double a)
{
radius=r;
angle=a;
}
void display()
{
cout<<"("<<radius<<","<<angle<<")";
}
double getr()
{
return radius;
}
double geta()
{
return angle;
}
};
class rec
{
private:
double xco;
double yco;
public:
rec()
{
xco=0.0;
yco=0.0;
}
rec(double x, double y)
{
xco=x;
yco=y;
}
rec(polar p)
{
float r=p.getr();
float a=p.geta();
xco=r*cos(a);
yco=r*sin(a);
}
void display()
{
cout<<"("<<xco<<","<<yco<<")";
}
};
void main()
{
clrscr();
19
rec recob;
polar polob(10.0,0.785398);
recob=polob;
cout<<"\npol=";
polob.display();
cout<<"\nrec=";
recob.display();
getch();
}
Q6.1 What does inheritance mean in C++? What are different forms of inheritance?
Give an example of each.
Ans:- Inheritance is a process by which objects of one class acquire the properties of
objects of another class. It is a mechanism of deriving a new class from old
one. Old class is referred as base class and new class is referred as derived
class.
Different forms of inheritance are
1. Single inheritance
2. Multiple inheritance
3. Hierarchical inheritance
4. Multilevel inheritance
5. Hybrid inheritance
1. Single inheritance:-A derived class with only one base class is called single
inheritance.
Eg.
class A
{
members of class A;
}
class B: public A
{
members of class B;
}
20
Multiple inheritance
class A
{
members of class A;
}
class B
{
members of class B;
}
class C : public B, public C
{
members of class C;
}
3. Hierarchical inheritance : When more than one classes are derived from a
single base class, it is called hierarchical inheritance.
Hierarchical inheritance
Eg.
class A
{
members of class A;
}
class B : public A
{
members of class B;
}
21
class C : public A
{
members of class C;
}
Multilevel inheritance
Eg.
class A
{
members of class A;
}
class B : public A
{
members of class B;
}
class C : public B
{
members of class C;
}
Hybrid inheritance
22
Eg.
class A
{
members of class A;
}
class B : public A
{
members of class B;
}
class C
{
members of class C;
}
where
colon indicates that the derived –class-name is derived from the base-class-
name.
visibility mode specifies whether the features of the base class are privately
derived or publicly derived. It is optional by default visibility mode is private.
23
Q6.5 What is virtual base class. When do we make a class virtual?
Ans:- When a derived class inherit the same characteristics through various paths,
than there is a duplication of characteristics. This can be avoided by making
the common base class as virtual base class. When a class is made a virtual
base class C++ takes necessary care to see that only one copy of that class is
inherited, regardless of how many inheritance paths exists between the virtual
base class and a derived class.
Eg.
Student
Test sports
Result
In above eg. result class inheriting same characteristics twice through test class
and sports class. this duplication can be avoided by making common base class
as a virtual base class.
Q7.2 How is polymorphism achieved at (i) compile time (ii) run time?
Ans:-
i) compile time polymorphism can be achieved by function overloading and
operator overloading. The overloaded functions are selected for processing by
matching arguments, both type and number . This information is known to the
compiler at compile time and therefore compiler is able to select appropriate
24
function at the compile time itself . This is called early binding or compile time
polymorphism.
Eg.
void box(int);
void box(int, int, int);
in above eg. box is a overloaded function.
ii) Run time polymorphism can be achieved by virtual functions. When the
function name is same in both the base and derived classes, the function in
base class is declared as a virtual function. At run time when it is known which
class object is under consideration the appropriate version of function is
invoked. Since the function is linked with a particular class munch later after
compilation, this process is known as late binding or run time polymorphism.
Eg.
class base
{
int x;
public:
virtual void show(){ }
};
class derived
{
int y;
public:
void show( ) { }
};
void main( )
{
base b;
derived d;
base *ptr;
ptr=&b;
ptr-> show( ); //call base class version
ptr=&d;
ptr->show( ); //call derived class version
}
Q7.5 What does this pointer point to? What are the application of this pointer?
Ans:- this pointer points to the object which invokes a member function.
For eg. A.max() will set pointer this to the address of the object A.
Application of this pointer
i) this pointer is automatically passed to a member function when it is called.It
acts as implicit argument to all the member functions.
Eg.
Class XYZ
{
int a;
};
25
private variable a can be used directly inside a member function, like
a=123;
ii) When a binary operator is overloaded using member function, the first
argument is passed implicitly using this pointer.
iii) this pointer is used to return the object it points to.
Eg.
return *this;
inside a member function will return the object that invoked the function.
Input stream
Output stream
26
Ifstream provides input operations. Contains
open( ),get(),getline(),read(),seekg() and tellg() functions.
Ofstream provides output operations. Contains open( ),put(), seekp(), tellp(),
and write() functions.
Fstream() provides support for simultaneous input and output
operations.Contains open() with default input mode. Inherits all the functions
from istream and ostream classes.
ii) Using member function open() of the class:- this method is useful to
open multiple files that use the same stream object.
Eg.
ofstream outob; //create stream for output
outob.open(“database1”) //connect stream to database1 file
outob.close(); //disconnect stream from database1
outob.open(“database2”) //connect stream to database2
outob.close(); //disconnect stream from database2
Q8.5 What is the difference between opening a file with constructor function and
opening a file with open() function? When is one method preferred over the
other?
Ans:- ans as above 8.4
Q8.6 What is file mode? Describe the various file mode options available?
Ans:- The second argument in the open( ) function specify the purpose of opening a
file for reading or writing, that argument is called file mode parameter.
General form of the function open() with two arguments is
Stream-object.open(“filename”,”mode);
Eg.
fstream ob1; //create object of fstream
ob1.open(“result”,”ios::app”) //open file in append mode
27
Various file mode parameter
Parameter Meaning
ios : : app Append to end of file
ios : : ate Go to end of file on opening
ios : : binary Binary file
ios : : in Open file for reading only
ios : : nocreate Open fails if the file does not
exist
ios : : noreplace Open files if the file already exist
ios : : out Open file for writing only
ios : : trunc Delete the contents of the file if it
exists
Q8.7 How many file objects would you need to create to manage the following
situations?
i) To process four files sequentially
ii) To merge two sorted files into a third file.
Ans:- i) To process four files sequentially : one stream object is required . open
file1 and attach it to stream object . As soon as the file1 work is over close
file1. Open file2 and attach it to same stream object with the file2, when
its work is over close it. Similarly work with file3 and file4 sequentially.
Eg.
Ofstream ob; // create stream for output
ob.open(“file1”); //connect stream to file1
……….
ob.close(); //close file1
ob.open(“file2); //connect stream to file2
………..
ob.close(); //close file2
………..
ii ) To merge two sorted files into a third file:- We need three stream
objects. Two separate input stream objects for handling the two input files
and one output stream object for handling the output file.
ifstream ob1,ob2; //create two input stream
ofstream ob3; //create one output stream
ob1.open(“infile1”);
ob2.open(“infile2”);
ob3.open(“outfile3”)
Q8.8 What do you mean by saving data in binary form in file?what are the
advantages of saving data in binary form?
Ans:- Saving data in binary form means values are stored in disk file in the same
format in which they are stored in the internal memory.
The binary input and output functions has the form
infile.read((char *) & v, sizeof(v));
28
outfile.wirte((char *) & v, sizeof(v));
The first argument is the address of variable v,
Length of that variable in bytes.
Advantages
i) The binary format is more accurate for storing data as it is stored in the
exact internal representation.
ii) There are no conversions while saving the data and therefore saving is
much faster.
Q8.9 Describe the various approaches by which we can detect the end of file
condition successfully.
Ans:-
Q8.10 What are command line arguments?
Ans:- File names supplied as arguments to main() function at the time of invoking
the program. These arguments are known as command line arguments.
Eg.
c>exam data results
where exam is name of file containing program
data and results are the filenames passed to the program as command line
arguments.
Q8.12 Explain in brief the different functions for manipulation of file pointers
Ans:- Functions for manipulation of file pointers are
i) seekg() :- moves get pointer(input) to a specified location.
ii) seekp() :- moves put pointer(output) to a specified location.
iii) tellg() :- gives the current position of the get pointer.
iv) Tellp() :- gives the current position of put pointer.
Q8.13 What are the functions used for performing I/O operations on files?
Ans:- Funcitons for performing I/O operations on files are
i) get() :- reads a single character from associated stream.
ii) put() :- writes a single character to associated stream.
iii) read() :-reads a block of binary data from associated stream.
iv) wirte() :-writes a block of binary data to associated stream.
29
NOTES ON DATA STRUCTURE
30
Q1.6 How are data and functions are organized in OOP?
Q6.3 We know that a private member of a base class is not inheritable. Is it anyway
possible for the objects of a derived class to access the private members of the
base class? If yes how? Remember the base class can’t be modified.
Q7.3 Discuss the different ways by which we can access public member functions of
an object.
Q7.4 Explain, with an example, how you would create space for an array of objects
using pointers.
Q6.7 In what order are the class constructors called when a derived class object is
created?
Q6.8 Class D is derived from class B. The class d does not contain any data
members of its own. Does the class D require constructors? If yes, why?
Q7.7 When do we make a virtual function pure? What are the implications of
making a function a pure virtual function?
31
32