cpp-brief.
cpp-brief.
C++ Cia
GROUP E
1. Compare and contrast multiple inheritance and
multilevel inheritance with the help of classes.
a) Multiple Inheritance is a feature of C++ where a class can inherit from more than one
classes. i.e one sub class is inherited from more than one base classes.
#include <iostream>
using namespace std;
class Area
{
public:
float area_calc(float l,float b)
{
return l*b;
}
};
class Perimeter
{
public:
float peri_calc(float l,float b)
{
return 2*(l+b);
}
};
int main()
{
Rectangle r;
r.get_data();
cout<<"Area = "<<r.area_calc(r.length,r.breadth);
cout<<"\nPerimeter = "<<r.peri_calc(r.length,r.breadth);
return 0;
}
OUTPUT:
Area = 11.73
Perimeter = 14.8
#include <iostream>
using namespace std;
class A
{
public:
void display()
{
cout<<"Base class content.";
}
};
class B : public A
{
};
3
class C : public B
{
};
int main()
{
C c;
c.display();
return 0;
}
OUTPUT:
void staff::getdata()
{
cout<<"Name:";
gets(name);
cout<<"Code:";
cin>>code;
}
void staff::display()
{
cout<<"Name:"<<name<<endl;
cout<<"Code:"<<code<<endl;
}
void typist::getdata()
{
cout<<"Speed:";
cin>>speed;
}
void typist::display()
{
cout<<"Speed:"<<speed<<endl;
}
int main()
{
typist t;
cout<<"Enter data"<<endl;
t.staff::getdata();
t.getdata();
cout<<endl<<"Display data"<<endl;
t.staff::display();
5
t.display();
getch();
return 0;
}
A derived class with two base classes and these two base classes have one common base class
is called
multiple inheritance.
Ambiguity in C++ occur when a derived class have two base classes and these two base classes
have one
common base class.
#include<iostream.h>
#include<conio.h>
class ClassA
{
public:
int a;
};
int d;
};
void main()
{
ClassD obj;
obj.b = 20;
obj.c = 30;
obj.d = 40;
Output :
A : 100
B : 20
C : 30
D : 40
Thus, this is how ambiguity is resolved in single and multiple inheritance in c++ using classes.
class features
{
public:
char abs;//Y or N
char ac;//Y or N
};
class prototype:public performance,public visual,public features//Multiple
Inheritence
{
public:
long estimate;//Estimated price
void estimatep()
{
if(engine<1500)
{
estimate+=200000;
}
else
{
estimate+=500000;
}
if(abs=='Y','y')
estimate+=45000;
if(ac=='Y','y')
estimate+=50000;
}
};
class automobile:private prototype//Single/Multilevel Inheritence
{
char name[30];
public:
void input()
{
estimate=0;
cout<<"Name of the car : ";
fflush(stdin);
gets(name);
cout<<"Performance\n";
cout<<"Engine Displacement(in cc) : ";
cin>>engine;
cout<<"Power(in BHP) : ";
cin>>power;
cout<<"Visual\n";
cout<<"Color : ";
cin>>color;
cout<<"Features\n";
cout<<"ABS(Y or N) : ";
8
cin>>abs;
cout<<"Air Conditioner(Y or N) : ";
cin>>ac;
estimatep();
}
void display()
{
system("cls");
double tax;
tax=estimate*0.18;
cout<<"Name : ";puts(name);
cout<<"-----------------------------------\n";
cout<<"Performance\n";
cout<<"Engine Displacement(in cc) : "<<engine<<endl;
cout<<"Power(in BHP) : "<<power<<endl;
cout<<"Visual\n";
cout<<"Color : "<<color<<endl;
cout<<"Features\n";
cout<<"ABS : "<<abs<<endl;
cout<<"Air Conditioner : "<<ac<<endl;
cout<<"-Estimated Price : "<<estimate<<endl;
cout<<"-Final Price : "<<double(estimate+tax)<<endl;
cout<<"\n-----------------------------------\n";
}
};
int main()
{
automobile car;
car.input();
car.display();
}
class Base
{
9
int x;
public:
virtual void fun() = 0;
int getX() { return x; }
};
int main(void)
{
Derived d;
d.fun();
return 0;
}
Output:
fun() called
Inheritance is the process of creating new classes, called derived classes, from existing
classes or base classes. The derived class inherits all the capabilities of the base class,
but can add embellishments and refinements of its own.
ADVANTAGES:
11
Since inception, C++ has been intended as an OOP language extending from its C
predecessor. A major concept behind OOP is polymorphism. Polymorphism allows
different objects of different types to conform to a common interface while uniquely
defining behavior. One form of polymorphism which is critical in OOP is inheritance.
EXAMPLE:
Here we have two classes Teacher and MathTeacher the MathTeacher class
inherits the Teacher class which means Teacher is a parent class and
MathTeacher is a child class. The child class can use the
property collegename of parent class.
Another important point to note is that when we create the object of child class it
calls the constructor of child class and child class constructor automatically calls
the constructor of base class.
12
#include <iostream>
using namespace std;
class Teacher {
public:
Teacher(){
cout<<"Hey Guys, I am a teacher"<<endl;
}
string collegeName = "Beginnersbook";
};
//This class inherits Teacher class
class MathTeacher: public Teacher {
public:
MathTeacher(){
cout<<"I am a Math Teacher"<<endl;
}
string mainSub = "Math";
string name = "Negan";
};
int main() {
MathTeacher obj;
cout<<"Name: "<<obj.name<<endl;
cout<<"College Name: "<<obj.collegeName<<endl;
cout<<"Main Subject: "<<obj.mainSub<<endl;
return 0;
}
Syntax :
We use Multiple inheritance when we want a child class to inherit from more
than one parent class.
Example : If we have a base class named as LivingThing. And this class has
function as breathe(). The Animal and Reptile classes inherit from it. Only
the Animal class overrides the method breathe(). The Snake class inherits from
the Animal and Reptile classes. It overrides their methods. And hence it can be
useful in such cases.
But, It is not prefered using multiple inheritance and use virtual inheritance
instead.
strcpy(this->name,name);
cout<<endl<<"Parameterized Constructor Called ('this' pointer used)";
}
void display()
{
cout<<endl<<"Registration number : "<<rno;
cout<<endl<<"Name : "<<name<<endl;
}
};
int main()
{
char a[]="S1",b[]="S2";
q8 stud1= q8(1741000,a);
cout<<endl<<"Student 1";
stud1.display();
q8 stud2= q8(1741000,b);
cout<<endl<<"Student 2";
stud2.display();
return 0;
}
MULTIPLE MULTILEVEL
Multiple Inheritance is an Inheritance Multilevel Inheritance is an Inheritance
type where a class inherits from more type that inherits from a derived class,
than one base class. making that derived class a base class
for a new class.
Multiple Inheritance is not widely used
because it makes the system more Multilevel Inheritance is widely used.
complex.
Multiple Inheritance has two class levels Multilevel Inheritance has three class
namely, base class and derived class. levels namely, base class, intermediate
class and derived class.
15
Syntax – Syntax -
class base_class1
class base_classname
{ properties; methods;};
{ properties; methods;};
class base_class2
class
{ properties; methods;}; intermediate_classname:visibility_mode
base_classname
{ properties; methods;};
{ properties; methods;};
{ properties; methods;};
16
Multiple Inheritance
Mammal Winged Animal
Bat
In C++ programming, a class can be derived from more than one parents. For example: A
class Bat is derived from base classes Mammal and WingedAnimal It makes sense because
bat is a mammal as well as a winged animal.
Program:-
#include <iostream>
using namespace std;
class Mammal {
public:
Mammal()
{
cout << "Mammals can give direct birth." << endl;
}
};
class WingedAnimal {
public:
WingedAnimal()
{
cout << "Winged animal can flap." << endl;
}
17
};
};
int main()
{
Bat b1;
return 0;
}
Multilevel Inheritance
Class A
Class B
Class C
18
In C++ programming, not only you can derive a class from the base class but you can
also derive a class from the derived class. This form of inheritance is known as
multilevel inheritance.
Program
#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 obj;
obj.display();
return 0;
}
Output:
Base class content
In this program, class C is derived from class B (which is derived from base class A).The obj
object of class C is defined in the main() function.When the display() function is called,
display() in class A is executed. It's because there is no display() function in class C and class
B.The compiler first looks for the display() function in class C. Since the function doesn't exist
there, it looks for the function in class B (as C is derived from B).The function also doesn't
exist in class B, so the compiler looks for it in class A (as B is derived from A).If display()
function exists in C, the compiler overrides display() of class A (because of member function
overriding).
19
};
class B:public A
{
protected:
int b;
public:
B(int x,int y):A(x)
{
b=y;
cout<<"\nClass B \n";
}
};
class C:public B
{
protected:
int c;
public:
C(int m,int n,int o):B(m,n)
{
c=o;
cout<<"\nClass C\n";
20
}
void disp()
{
cout<<"\n Your Salary is "<<a;
cout<<"\n Your Broher's Brother is "<<b;
cout<<"\n Your Sister's Salry is "<<c;
}
void compare()
{
if((a>b)&&(a>c))
{
cout<<"\nYour are earning more. Cheer up
hardworking person\n";
}
else if((c>b)&&(a<c))
{
cout<<"\nWomen are ahead of men.Dont get
demotivated.You only need to power up by "<<((c-a)/(c+a))*100<<"%";
}
else if((b>c)&&(a<b))
{
cout<<"\n:)\n";
cout<<"\nDont get demotivated.You only need
to power up by "<<((b-a)/(b+a))*100<<"%";
}
else
{
cout<<"\nWork hard ! :)\n";
}
}
};
int main()
{
int a,b,c;
cout<<"What's is your salary\t";
21
cin>>a;
cout<<"What's your brother's salary\t";
cin>>b;
cout<<"What's your sister's salary\t ";
cin>>c;
C c1(a,b,c);
c1.disp();
cout<<"\n COMPARE\n";
c1.compare();
}
12. Explain early binding and late binding with suitable example.
// outputs.
#include<iostream>
class Base
public:
};
public:
};
int main(void)
// function.
bp->show();
return 0;
Assuming c begin your single character.cin>>c and cin.get() both takes a character
input. The difference being >> is an operator which returns istreamobject, whereas
istream::get() returns traits::int_type(If there is input) or traits::eof()(If no
input or input in bad format). You cannot take newline('\n') or Horizontal Tab('\t') as input
using cin>>c. To do so you need to enable noskipwsflag or disable skipws flag.
14.Compare the input and output facilities in C++ differ from C language?
C++ approach differs in the following main points:
it is type-safe. There is no possibility to mismatch the format specifier and the argument type.
it exposes the complexity of C streams and allows the programmer to access, extend, and
modify every part of it, which means
user-defined types can support I/O, and far more standard types come with I/O as well (both
C and C++ have complex number types, but only C++ gives them I/O)
C++ streams can be attached to TCP sockets, memory-mapped files, and other custom
sources/sinks, they can compress/decompress data on the fly (e.g. streaming a gzipped file),
split and join, etc
each stream has its own locale and the facets can be modified as well: you can stream in a
CSV file treating commas as whitespace. You can stream in from a UTF-8 file and out into a
GB18030 one.
the exposed complexity is overwhelming to many programmers.
24
15. Both cin and getline() function can be used for reading a
string. Comment.
In most program environments, the standard input by default is the keyboard, and the
C++ stream object
defined to access it is cin(Standard Input).
For formatted input operations, cin is used together with the extraction operator, which is
written as
>> (i.e., two "greater than" signs). This operator is then followed by the variable where the
extracted
data is stored. For example:
int age;
cin >> age;
getline() is a standard library function in C++ and is used to read a string or a line from input
stream.
It is present in the <string> header.
So basically, what the getline function does is extracts characters from the input stream and
appends it
to the string object until the delimiting character is encountered.
Since cin does not read complete string using spaces, stings terminates as you input space.
While
cin.getline() – is used to read unformatted string (set of characters) from the standard input
device
(keyboard). This function reads complete string until a give delimiter or null match.
In this program will read details name, address, about of a person and print in different lines,
name
will contain spaces and dot, address will contain space, commas, and other special
characters, same
about will also contains mixed characters. We will read all details using cin.getline() function
and
print using cout.
int main()
{
char
name[MAX_NAME_LENGTH],address[MAX_ADDRESS_LENGTH],about[MAX_ABOUT_LE
NGTH];
return 0;
}
Thus, this is how both cin and getline() function can be used for reading a string.
Character pointer (char*) has overloaded output operator (operator<<), and prints
underlying C-style string instead of adress of a pointer. This overload exists in order to
support code like this:
std::cout << "some string";
26
“”some string type” type is actually const char*, without the overload it would print an
adress of string instead of the string itself.Void pointer (void*), or any other pointer type
(AFAIK) doesn't provide this kind of overload, so the printed value is pointer address.
The gets() function reads characters from stdin and stores them in str until a newline character or end of file is
found.
gets() Parameters
str: Pointer to an character array that stores the characters from stdin.
#include <iostream>
#include <cstdio>
int main()
char str[100];
gets(str);
return 0;
C++ puts()
The puts() function in C++ writes a string to stdout.
The puts() function takes a null terminated string str as its argument and writes it to stdout. The terminating
null character '\0' is not written but it adds a newline character '\n' after writing the string.
puts() Parameters
On success, the puts() function returns a non-negative integer. On failure it returns EOF and sets the error
indicator on stdout.
#include <cstdio>
int main()
puts(str1);
puts(str2);
return 0;
Happy Birthday
We can use the setf() function to configure formatting for the cout object. We pass the
setf() function arguments made up of ios_base class constants such as ios_base::boolalpha to
display bool values as true or false instead of 1 or 0, and ios_base::showpoint to show a
trailing decimal point.
#include <iostream>
using namespace std;
int main()
{
// Turn on showpos and scientific flags.
cout.setf(ios::showpos);
cout.setf(ios::scientific);
cout << 123 << " " << 123.23 << " ";
return 0;
}
OUTPUT:+123 +1.232300e+002
30