0% found this document useful (0 votes)
2 views40 pages

Object Oriented Programming in c

The document provides an overview of Object-Oriented Programming (OOP) in C++, detailing its key features such as inheritance, encapsulation, abstraction, polymorphism, method overriding, and method overloading. It explains the concepts of classes and objects, constructors and destructors, and the use of static data members and member functions. Additionally, it includes examples of C++ code demonstrating the implementation of a quadratic equation solver and the use of scope resolution operator.

Uploaded by

user-249440
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views40 pages

Object Oriented Programming in c

The document provides an overview of Object-Oriented Programming (OOP) in C++, detailing its key features such as inheritance, encapsulation, abstraction, polymorphism, method overriding, and method overloading. It explains the concepts of classes and objects, constructors and destructors, and the use of static data members and member functions. Additionally, it includes examples of C++ code demonstrating the implementation of a quadratic equation solver and the use of scope resolution operator.

Uploaded by

user-249440
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

OBJECT ORIENTED PROGRAMMING IN C++

What is OOPS?

Object-Oriented Programming (OOP) is a programming model that uses


classes and objects. It’s utilized to break down a software program into
reusable code blueprints (called classes) that you may use to build specific
instances of things. Object-oriented programming languages include
JavaScript, C++, Java, and Python, to name a few.

Top Features of OOPS


1. Inheritance
In layman’s terms, the attributes that you inherit from your parents are a
simple illustration of inheritance. Classes may inherit characteristics from
other classes thanks to inheritance. Parent classes, in other words, extend
properties and behaviors to child classes. Reusability is aided via inheritance.
Prototyping is another name for inheritance in JavaScript. A prototype object
serves as a base from which another object may derive its features and
actions. Thus, you may use multiple prototype object templates to form a
prototype chain. Inheritance is passed down from one generation to the next.
parent
Consider the application Polygon, which represents several Shapes. We’re
expected to make two distinct sorts of polygons: a Rectangle and a Triangle.
2. Encapsulation
Encapsulation is the process of enclosing all critical information inside an
object and only revealing a subset of it to the outside world. For example,
code inside the class template defines attributes and behaviors.
The data and methods are then enclosed in the object when it is created from
the class. Inside a class, encapsulation conceals the underlying software code
implementation and the internal data of the objects. Encapsulation
necessitates designating certain fields as private while others are made
public.
• Methods and attributes only available from other methods in the same
class make up the private/internal interface.
• Methods and attributes that are available from outside the class are
known as the public / external interface.
3. Abstraction
Abstraction refers to the user’s interaction with just a subset of an object’s
characteristics and operations. To access a complicated item, abstraction
uses simpler, high-level techniques.
• Simple items are used to show complexity.
• Keep complicated information hidden from the user.
Simple classes are used to indicate complexity in abstraction. Encapsulation
is an extension of abstraction.
A Real-Life Example of Abstraction
Advantages of Abstraction
• It simplifies the process of seeing things in their entirety.
• Code duplication is avoided, and reusability is increased.
• Because just the most necessary information is shown to the user, it
helps to enhance the security of an application or software.
4. Polymorphism
Polymorphism refers to the creation of items that have similar behavior. For
example, objects may override common parent behaviors with particular child
behaviors through inheritance. Method overriding and method overloading are
two ways that polymorphism enables the same method to perform various
actions.
Examine how Polymorphism and the actual world are interconnected with
examples.
Take, for example, your mobile phone. It has the capability of storing your
Contacts. Consider the following scenario: you wish to store two numbers for
one individual. You may do this by storing the second number under the same
name as the first.
Consider the following scenario: you wish to store two numbers for the same
individual in an object-oriented language such as Java. Create a function that
will accept as arguments two integers and the name of the individual to some
function void createContact that will be defined later (String name, int
number1, int number2).
5. Method Overriding
Method overriding is used in runtime polymorphism. When a child class
overrides a parent class’s method, the child class might offer an alternative
implementation.
Consider a family of three, consisting of the father, mother, and son. The
father makes the decision to teach his kid to shoot. As a result, he brings him
to the range with his favorite rifle and teaches him how to aim and fire at
targets. The father, on the other hand, is right-handed, while the kid is left-
handed. So they each have their own way of handling the pistol! Because of
their differing orientations, the father was concerned that he may not be able
to teach his son how to shoot.
The son, on the other hand, was astute and chose to flip his father’s hands,
putting his dominant hand on the trigger rather than the father’s. Specifically,
the right hand. By significantly changing the learning process, the son was
able to grasp the skill of shooting!
Method overriding is the term used in programming to describe this idea.
6. Method Overloading
Method overloading is used in Compile Time Polymorphism. Although two
methods or functions may have the same name, the number of arguments
given into the method call may vary. Therefore, depending on the number of
parameters entered, you may obtain different results.
With the help of a simple example, it may be comprehended in simple words.
A class addition contains two add() methods, one with arguments int a and int
b and the other with three integer parameters, int a, int b, and int c. As a
result, the add() function is considered overloaded.
The amount of arguments given in the method calling statement determines
which method is performed. For example, add(20,30) calls the two-parameter
add() function, whereas add(10,20,30) calls the three-parameter add method
7. Objects
An object is a self-contained segment with the attributes and processes
needed to make data usable in programming terms. From an object-oriented
perspective, objects are the main building pieces of programs. In each
application you create, you may employ a variety of objects of various sorts.
Each kind of object is derived from a specific class of that type. Consider an
object to be a sculpt of the real-world perceptions, processes, or objects that
are important to the application you’re designing.
A variable, function, or data structure may all be considered an object. The
term “object” in object-oriented programming refers to a specific instance of a
class. Objects are used in software development to combine data components
with methods that alter them, allowing for the usage of abstract data
structures. Objects in object-oriented programming are answers to the idea of
inheritance, resulting in improved program dependability, simpler software
maintenance, library administration, and task division in programmer teams.
Of basic terms, “Objects” are the fundamental data types in object-oriented
programming languages and are used to build object-oriented programming.
8. Classes
In the oops concept, a class is a construct that is used to describe an
individual type. The class is instantiated into instances of itself – referred to as
class instances or simply objects. A class defines ingredient members that
allow its instances to have position and behavior. Member variables or
instance variables facilitate a class instance to maintain its position. On the
other hand, other kinds of members, especially methods, allow the behavior of
class instances. Simply classes consequently define the type of their
instances. A class usually represents a person, place or thing, or something.
For example, a “Bird” class would symbolize the properties and functionality of
birds. A single, particular bird would be an instance of the “Bird” class, an
object of the type “Bird”. There is a set of access specifiers in classes. private
(or class-private) specifiers restrict the entrance to the class itself. Only the
methods that are elements of a similar class only can access private
members. protected (or class-protected) specifies enables the class itself and
all classes under it (sub-classes) to access the member and public means that
member can be accessed by its name using any code.
9. Constructors and Destructors
Constructors in most object-oriented languages have the same name as the
class and are public. Constructors may be overloaded, which means that
multiple argument lists can be used with the same name. The function
Object() { [native code] } in PHP 5.0 is the function _construct (). Normally,
attribute values would be initialised in a function Object() { [native code] }. The
_destruct() method is optional, although it might be used to implement code
that cleans up once an object is destroyed, such as shutting files or database
connections.
OOP Advantages
• Complex things are modeled as repeatable, basic structures in OOP.
• Thus, OOP objects are reusable and may be utilized in several
applications.
• Modularity for easier troubleshooting.
• Classes are easier to debug since they generally include all relevant
information.
• Reuse of code through inheritance.

UNIT-1
Ques-Write a program using class to solve a quadratic equation.
--#include <iostream>
#include <cmath>
using namespace std;

// create a class
class Quadratic {
// private data members
private:
float a, b, c;

// public functions
public:
// getCoefficient() function to insert
// the coefficients of the equation
void getCoefficient() {
cout << "Enter Coefficient of a:";
cin >> a;

cout << "Enter Coefficient of b:";


cin >> b;

cout << "Enter Coefficient of c:";


cin >> c;
}

// roots() function to find out the nature and


// values of both root of the equation
void roots() {
// float type variable for operations
float root_1, root_2, discriminant, real_part, imaginary_part;

// calculating discriminant
discriminant = b * b - 4 * a * c;

// if discriminant is greater than 0 the


// both the roots are real different
if (discriminant > 0) {
// calculating first root
root_1 = (-b + sqrt(discriminant)) / (2 * a);

// calculating second root


root_2 = (-b - sqrt(discriminant)) / (2 * a);

// printing them
cout << "Roots are real and different." << endl;
cout << "Root 1 = " << root_1 << endl;
cout << "Root 2 = " << root_2 << endl;
}

// if discriminant is equal to 0 then


// both the root are real and same
else if (discriminant == 0) {
cout << "Roots are real and same." << endl;

// calculating roots
root_1 = -b / (2 * a);
cout << "Root 1 = Root 2 =" << root_1 << endl;
}

// else roots are complex and different


else {
// calculating real part of roots
real_part = -b / (2 * a);

// calculating imaginary part of roots


imaginary_part = sqrt(-discriminant) / (2 * a);

// printing them
cout << "Roots are complex and different." << endl;
cout << "Root 1 = " << real_part << "+" << imaginary_part << "i" << endl;
cout << "Root 2 = " << real_part << "-" << imaginary_part << "i" << endl;
}
}
};

int main() {
// create a class
Quadratic Q;

// calling getCoefficient() function to insert coefficients value


Q.getCoefficient();

// calling roots() function to find roots


Q.roots();

return 0;
}
Ques-What do you mean by static data member and static member functions? Explain it with
example.

S tatic Data Member

A data member of a class can be qualified as static. The properties of a static member

variable are similar to that of Cs static variable. A static data member has certain

special characteristics. They are:-

• It is initialized to zero when the first object of its class is created. No other

initialization is permitted.

• Only one copy of that member is created for the entire class and is shared

by all the objects of that class, no matter how many objects are created.
• It is visible only within the class, but its lifetime is the entire program.
A static variable is normally used to maintain value common to the entire class. For

e.g, to hold the count of objects created. Note that the type and scope of each static

member variable must be declared outside the class definition. This is necessary

because the static data members are stored separately rather than as a part of an

object.

static data_type member_name;


#include <iostream>
using namespace std;
class Demo
{
public:
static int ABC;
};

//defining
int Demo :: ABC =10;

int main()
{

cout<<"\nValue of ABC: "<<Demo::ABC;


return 0;
}
Output: Value of ABC: 10
Ques-Explain uses of scope resolution operator giving example.
In C++, the scope resolution operator is ::. It is used for the following
purposes.
1 To access a global variable when there is a local variable with
same name:
// C++ program to show that we can access a global variable
// using scope resolution operator :: when there is a local
// variable with same name
#include<iostream>
using namespace std;

int x; // Global x

int main()
{
int x = 10; // Local x
cout << "Value of global x is " << ::x;
cout << "\nValue of local x is " << x;
return 0;
}
Output
Value of global x is 0
Value of local x is 10

2 To define a function outside a class.


// C++ program to show that scope resolution operator :: is
// used to define a function outside a class
#include <iostream>
using namespace std;

class A {
public:
// Only declaration
void fun();
};

// Definition outside class using ::


void A::fun() { cout << "fun() called"; }

int main()
{
A a;
a.fun();
return 0;
}
Output
fun() called
Ques-How class is declared ? How objects are created ? And member functions are called ?
Class in C++ is the building block that leads to Object-Oriented
programming. It is a user-defined data type, which holds its own data
members and member functions, which can be accessed and used by
creating an instance of that class. A C++ class is like a blueprint for an
object. For Example: Consider the Class of Cars. There may be many
cars with different names and brands but all of them will share some
common properties like all of them will have 4 wheels, Speed
Limit, Mileage range, etc. So here, Car is the class, and wheels, speed
limits, and mileage are their properties.
• A Class is a user-defined data type that has data members
and member functions.
• Data members are the data variables and member functions
are the functions used to manipulate these variables together,
these data members and member functions define the
properties and behavior of the objects in a Class.
• In the above example of class Car, the data member will
be speed limit, mileage, etc, and member functions can
be applying brakes, increasing speed, etc.
An Object is an instance of a Class. When a class is defined, no
memory is allocated but when it is instantiated (i.e. an object is
created) memory is allocated.
Defining Class and Declaring Objects
A class is defined in C++ using the keyword class followed by the
name of the class. The body of the class is defined inside the curly
brackets and terminated by a semicolon at the end.
Declaring Objects
When a class is defined, only the specification for the object is defined;
no memory or storage is allocated. To use the data and access
functions defined in the class, you need to create objects.
Syntax
ClassName ObjectName;

Accessing data members and member functions: The data members


and member functions of the class can be accessed using the dot(‘.’)
operator with the object. For example, if the name of the object
is obj and you want to access the member function with the
name printName() then you will have to write obj.printName().
Accessing Data Members
The public data members are also accessed in the same way given
however the private data members are not allowed to be accessed
directly by the object. Accessing a data member depends solely on the
access control of that data member. This access control is given
by Access modifiers in C++. There are three access modifiers: public,
private, and protected.
// C++ program to demonstrate accessing of data members
#include <bits/stdc++.h>
using namespace std;
class Geeks {
// Access specifier
public:
// Data Members
string geekname;
// Member Functions()
void printname() { cout << "Geekname is:" << geekname; }
};
int main()
{
// Declare an object of class geeks
Geeks obj1;
// accessing data member
obj1.geekname = "Abhi";
// accessing member function
obj1.printname();
return 0;
}
Output
Geekname is:Abhi

Member Functions in Classes


There are 2 ways to define a member function:
• Inside class definition
• Outside class definition
Ques-What are different ways of defining member functions ? Give examples.
--What Is Member Function In C++?

As specified before, member functions are functions defined within a class. They
can access the values of the data members and can also carry out operations on
the data members. Their definition may be included in or excluded from the class
body. A member function in C++ can access both public and private class members.

Syntax for Member Function in C++

// Member function declaration


returnType functionName (arguments)
{//function body
};

• The functionName refers to the name of the function, with


the returnType specifying the data type of its return value.

• The arguments refer to the parameters the member function can take.
• The curly brackets {} contain the function body, i.e., the operations that are
performed on the data members of the class.
Additional points to note about a member function in C++ is that it can access the
private data of members, whereas a non-member function is unable to do so.

• Also, they can be called by another member function directly without using a
dot operator.

• Member function makes the program modular by increasing code reusability


and making it easier to understand, hence making the code maintainable.

• Member functions also provide the ability to restrict access to the data of
members of the class. This can be done by making specific functions private,
thus ensuring that only the class itself may access or modify sensitive data.
Let us understand how member functions are declared and defined in
a C++ program with the help of an example:

#include<iostream>
using namespace std;

class add{
private:
//Data Members
int a,b,c;

public:
//Member Function
void sum(){
cout <<"Enter 2 values:";
cin >>a>>b;
c = a+b;
cout<<"Sum is ="<< c << endl;}
};

int main(){
add p;
p.sum();
}
Output:

Enter 2 values: 3 3
Sum is = 6
How To Define A Member Function In C++?

There are mainly two ways to define a member function in C++. They are-

1. Inside the class definition

2. Outside the class definition.


We will discuss both of these ways in greater detail in the sections ahead, along
with the help of examples.

Defining Member Function In C++ Inside The Class Definition

A member function can be both declared and defined within a class itself. When a
member function is defined within a class, it is referred to as an inline function. All of
the constraints and limitations that apply to inline functions also apply to functions
declared within a class.

Syntax:

class MyClass{
private:
//Data Members variables

public:
//Member Function
returnType functionName(argument){
//Function Definition
}
};
Here,

• In the code given above, you can see how a member function is declared and
defined inside a class in C++.

• There is a class ‘MyClass, which contains the data members, and the member
function named ‘functionName’, which is nothing but a normal function.
Ques- What are the drawback of procedural oriented programming?Explain OBJECT
ORIENTED PARADIGM(OOAD).

• The code re-usability feature is not present in the procedure oriented


programming.we have to write the same programming code to many
times .
• We can not perform encapsulation ,inheritance etc in the procedure
oriented programming.
• The only drawback is that, for really large and complex applications, it’s difficult to
manage the code complexity. The procedural paradigm provides poor tools for
encapsulation and extensibility. You can only go so far with “modules” of
procedures.

• For writing small or modest-sized apps, procedural is quick and easy. For
everyting else, you want to use object-oriented programming. Hands-down, the
best language for this is Pharo: read Why Pharo Might be the Future of Software
Development
The object-oriented (OO) paradigm took its shape from the
initial concept of a new programming approach, while the
interest in design and analysis methods came much later. OO
analysis and design paradigm is the logical result of the wide
adoption of OO programming languages.

Introduction to OO Paradigm
OO paradigm is a significant methodology for the development of
any software. Most of the architecture styles or patterns such as
pipe and filter, data repository, and component-based can be
implemented by using this paradigm.

Basic concepts and terminologies of object–oriented systems −


Object

An object is a real-world element in an object–oriented


environment that may have a physical or a conceptual existence.
Each object has −

• Identity that distinguishes it from other objects in the


system.
• State that determines characteristic properties of an object
as well as values of properties that the object holds.
• Behavior that represents externally visible activities
performed by an object in terms of changes in its state.

Objects can be modeled according to the needs of the application.


An object may have a physical existence, like a customer, a car,
etc.; or an intangible conceptual existence, like a project, a
process, etc.

Ques-what are static data members in c++ how they can declared and defined?

--Static data members are class members that are declared


using static keywords. A static member has certain special
characteristics which are as follows:
• Only one copy of that member is created for the entire class
and is shared by all the objects of that class, no matter how
many objects are created.
• It is initialized before any object of this class is created, even
before the main starts.
• It is visible only within the class, but its lifetime is the entire
program.
Syntax:
static data_type data_member_name;

Below is the C++ program to demonstrate the working of static data


members:

• C++

// C++ Program to demonstrate


// the working of static data member
#include <iostream>
using namespace std;

class A {
public:
A()
{
cout << "A's Constructor Called " <<
endl;
}
};

class B {
static A a;

public:
B()
{
cout << "B's Constructor Called " <<
endl;
}
};

// Driver code
int main()
{
B b;
return 0;
}

Output
B's Constructor Called

Static members are only declared in a class declaration, not defined.


They must be explicitly defined outside the class using the scope
resolution operator.

Accessing a Static Member


As told earlier, the static members are only declared in the class
declaration. If we try to access the static data member without an
explicit definition, the compiler will give an error.
Below is the C++ program to show when static member ‘a’ is accessed
without explicit definition:
• C++

// C++ Program to demonstrate


// the Compilation Error occurred
// due to violation of Static
// Data Memeber Rule
#include <iostream>
using namespace std;

class A {
int x;

public:
A()
{
cout << "A's constructor called " <<
endl;
}
};

class B {
static A a;

public:
B()
{
cout << "B's constructor called " <<
endl;
}
static A getA()
{
return a;
}
};

// Driver code
int main()
{
B b;
A a = b.getA();
return 0;
}

Output
Compiler Error: undefined reference to `B::a'
Explanation: Here static member ‘a’ is accessed without explicit
definition. If we add the definition, the program will work fine and call
A’s constructor.
Defining Static Data Member
To access the static data member of any class we have to define it
first.
Below is the C++ program to show how to resolve the above error:

• C++

// C++ program to access static data


// member with explicit definition
#include <iostream>
using namespace std;

class A {
int x;

public:
A()
{
cout << "A's constructor called " <<
endl;
}
};

class B {
static A a;

public:
B()
{
cout << "B's constructor called " <<
endl;
}
static A getA()
{
return a;
}
};

// Definition of a
A B::a;
// Driver code
int main()
{
B b1, b2, b3;
A a = b1.getA();

return 0;
}

Output
A's constructor called
B's constructor called
B's constructor called
B's constructor called
Ques-What is scope resolution operator?

--Scope resolution operator in C++ is one of the essential operators which


is used to identify and access the entities that are defined outside the
current scope of a program. In simple terms, it allows a programmer to
access global or namespace-level entities within a function or a class. This
article discusses scope resolution operation in C++, its syntax, its purpose,
and applications of scope resolution operator in C++.

What is Scope Resolution Operator in C++?


The scope resolution operator in C++ is represented by two colons (::) and
is used to access entities that are defined outside the current scope of a
program. This operator is also known as the global scope operator.

Let’s take an example to understand more clearly, suppose we have two


integer variables defined as valuation, one is declared globally and one
locally. Both integer variables have different scopes and to access the
global variable valuation inside the local scope, the resolution operator "::"
is used as follows:

Code Implementation

• C++

#include<bits/stdc++.h>
using namespace std;
// global variable
int valuation = 1000000;
int main(){
// local variable
int valuation = 100000;
cout << "Value of the variable valuation in local scope: " << valuation <<"\n";
cout << "Value of the variable valuation in Global scope: " << ::valuation << "\n";
return 0;
}

Output:

Value of the variable valuation in local scope: 100000

Value of the variable valuation in Global scope: 1000000

Ques-EXPLAIN
ENCAPSULATION
--Encapsulation in C++ is defined as the wrapping up of data and
information in a single unit. In Object Oriented Programming,
Encapsulation is defined as binding together the data and the
functions that manipulate them.
Consider a real-life example of encapsulation, in a company, there are
different sections like the accounts section, finance section, sales
section, etc. Now,
The finance section handles all the financial transactions and

keeps records of all the data related to finance.
• Similarly, the sales section handles all the sales-related
activities and keeps records of all the sales.
Now there may arise a situation when for some reason an official from
the finance section needs all the data about sales in a particular
month.
In this case, he is not allowed to directly access the data of the sales
section. He will first have to contact some other officer in the sales
section and then request him to give the particular data.
This is what Encapsulation is. Here the data of the sales section and
the employees that can manipulate them are wrapped under a single
name “sales section”.
Two Important property of Encapsulation
1. Data Protection: Encapsulation protects the internal state of
an object by keeping its data members private. Access to and
modification of these data members is restricted to the class’s
public methods, ensuring controlled and secure data
manipulation.
2. Information Hiding: Encapsulation hides the internal
implementation details of a class from external code. Only the
public interface of the class is accessible, providing
abstraction and simplifying the usage of the class while
allowing the internal implementation to be modified without
impacting external code.
CLASS ND OBJECT

--C++ Class Definitions

When you define a class, you define a blueprint for a data type.
This doesn't actually define any data, but it does define what the
class name means, that is, what an object of the class will consist
of and what operations can be performed on such an object.

A class definition starts with the keyword class followed by the


class name; and the class body, enclosed by a pair of curly
braces. A class definition must be followed either by a semicolon
or a list of declarations. For example, we defined the Box data
type using the keyword class as follows −

class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};

The keyword public determines the access attributes of the


members of the class that follows it. A public member can be
accessed from outside the class anywhere within the scope of the
class object. You can also specify the members of a class
as private or protected which we will discuss in a sub-section.

Define C++ Objects


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
NESTED CLASS
--A nested class is a class which is declared in another enclosing class.
A nested class is a member and as such has the same access rights as
any other member. The members of an enclosing class have no special
access to members of a nested class; the usual access rules shall be
obeyed.
For example, program 1 compiles without any error and program 2
fails in compilation.
Program 1
#include<iostream>

using namespace std;

/* start of Enclosing class declaration */


class Enclosing {
private:
int x;

/* start of Nested class declaration */


class Nested {
int y;
void NestedFun(Enclosing *e) {
cout<<e->x; // works fine: nested class can access
// private members of Enclosing class
}
}; // declaration Nested class ends here
}; // declaration Enclosing class ends here
int main()
{

Program 2
#include<iostream>

using namespace std;

/* start of Enclosing class declaration */


class Enclosing {

int x;

/* start of Nested class declaration */


class Nested {
int y;
}; // declaration Nested class ends here

void EnclosingFun(Nested *n) {


cout<<n->y; // Compiler Error: y is private in Nested
}
}; // declaration Enclosing class ends here

int main()
{

UNIT 2
Ques-What do you mean by constructor overloading? Explain it with example.

--The use of multiple constructors in the same class is known as Constructor Overloading.

The constructor must follow one or both of the two rules below.

• All the constructors in the class should have a different number of parameters.
• It is also allowed in a class to have constructors with the same number of parameters
and different data types.
We can have more than one constructor in a class with same name, as
long as each has a different list of arguments.
• Overloaded constructors essentially have the same name
(exact name of the class) and different by number and type of
arguments.
• A constructor is called depending upon the number and type
of arguments passed.
• While creating the object, arguments must be passed to let
compiler know, which constructor needs to be called.
• // C++ program to illustrate
• // Constructor overloading
• #include <iostream>
• using namespace std;

• class construct
• {

• public:
• float area;

• // Constructor with no parameters
• construct()
• {
• area = 0;
• }

• // Constructor with two parameters
• construct(int a, int b)
• {
• area = a * b;
• }

• void disp()
• {
• cout<< area<< endl;
• }
• };

• int main()
• {
• // Constructor Overloading
• // with two different constructors
• // of class name
• construct o;
• construct o2( 10, 20);

• o.disp();
• o2.disp();
• return 1;
• }

Output:
0
200
Ques-Explain the various unformatted and formatted I/O operations.
UNFORMATED I/O Using objects cin and cout for the input and the
output of data of various types is possible because of overloading of
operator >> and << to recognize all the basic C++ types. The
operator >> is overloaded in the istream class and operator << is
overloaded in the ostream class.
The general format for reading data from the keyboard:
cin >> var1 >> var2 >> …. >> var_n;
Here, var1, var2, ……, varn are the variable names that are

declared already.
• The input data must be separated by white space characters
and the data type of user input must be similar to the data
types of the variables which are declared in the program.
• The operator >> reads the data character by character and
assigns it to the indicated location.
• Reading of variables terminates when white space occurs or
character type occurs that does not match the destination
type.
Program 1:
// C++ program to illustrate the
// input and output of the data
// entered by user
#include <iostream>
using namespace std;

// Driver Code
int main()
{
int data;
char val;

// Input the data


cin >> data;
cin >> val;

// Print the data


cout << data << " " << val;

return 0;
}

Output:

• FORMATED I/O If we want to add + sign as the prefix of out


output, we can use the formatting to do so:
• stream.setf(ios::showpos)
If input=100, output will be +100

• If we want to add trailing zeros in out output to be shown


when needed using the formatting:
• stream.setf(ios::showpoint)
If input=100.0, output will be 100.000

Note: Here, stream is referred to the streams defined in c++ like cin,
cout, cerr, clog.
There are two ways to do so:
1. Using the ios class or various ios member functions.
2. Using manipulators(special functions)
I.Formatting using the ios members:
The stream has the format flags that control the way of
formatting it means Using this setf function, we can set the
flags, which allow us to display a value in a particular format.
The ios class declares a bitmask enumeration called fmtflags
in which the values(showbase, showpoint, oct, hex etc) are
defined. These values are used to set or clear the format flags.
Few standard ios class functions are:
1. width(): The width method is used to set the required
field width. The output will be displayed in the given
width
2. precision(): The precision method is used to set the
number of the decimal point to a float value
3. fill(): The fill method is used to set a character to fill
in the blank space of a field
4. setf(): The setf method is used to set various flags for
formatting output
5. unsetf(): The unsetf method is used To remove the
flag setting
Ques-Write a program to add two complex numbers. Use constructors only.
Given two complex numbers of the form and the task is to add these
two complex numbers.
Here the values of real and imaginary numbers are passed while
calling the parameterized constructor and, with the help of a
default(empty) constructor, the function addComp is called to get the
addition of complex numbers.
Illustration: Input: a1 = 4, b1 = 8
a2 = 5, b2 = 7
Output: Sum = 9 + i15

Explanation: (4 + i8) + (5 + i7)


= (4 + 5) + i(8 + 7)
= 9 + i15

Input: a1 = 9, b1 = 3
a2 = 6, b2 = 1
Output: 15 + i4

// C++ Program to Add Two Complex Numbers

// Importing all libraries

#include<bits/stdc++.h>
using namespace std;

// User Defined Complex class

class Complex {

// Declaring variables

public:

int real, imaginary;

// Constructor to accept

// real and imaginary part

Complex(int tempReal = 0, int tempImaginary = 0)

real = tempReal;

imaginary = tempImaginary;

// Defining addComp() method

// for adding two complex number

Complex addComp(Complex C1, Complex C2)

// creating temporary variable

Complex temp;

// adding real part of complex numbers

temp.real = C1.real + C2.real;

// adding Imaginary part of complex numbers

temp.imaginary = C1.imaginary + C2.imaginary;


// returning the sum

return temp;

};

// Main Class

int main()

// First Complex number

Complex C1(3, 2);

// printing first complex number

cout<<"Complex number 1 : "<< C1.real

<< " + i"<< C1.imaginary<<endl;

// Second Complex number

Complex C2(9, 5);

// printing second complex number

cout<<"Complex number 2 : "<< C2.real

<< " + i"<< C2.imaginary<<endl;

// for Storing the sum

Complex C3;

// calling addComp() method

C3 = C3.addComp(C1, C2);

// printing the sum


cout<<"Sum of complex number : "

<< C3.real << " + i"

<< C3.imaginary;

// This code is contributed by chitranayal

Output
Complex number 1 : 3 + i2
Complex number 2 : 9 + i5
Sum of complex number : 12 + i7

Time Complexity: O(1)


Auxiliary Space: O(1)
Ques-. Explain various manipulators used for formatting the console I/O.
--Manipulators are helping functions that can modify
the input/output stream. It does not mean that we change the value of
a variable, it only modifies the I/O stream using insertion (<<) and
extraction (>>) operators.
• Manipulators are special functions that can be included in the
I/O statement to alter the format parameters of a stream.
• Manipulators are operators that are used to format the data
display.
• To access manipulators, the file iomanip.h should be included
in the program.

For example, if we want to print the hexadecimal value of 100 then we


can print it as:
cout<<setbase(16)<<100

Types of Manipulators There are various types of manipulators:


1. Manipulators without arguments: The most important
manipulators defined by the IOStream library are provided
below.
• endl: It is defined in ostream. It is used to enter a new
line and after entering a new line it flushes (i.e. it
forces all the output written on the screen or in the
file) the output stream.
• ws: It is defined in istream and is used to ignore the
whitespaces in the string sequence.
• ends: It is also defined in ostream and it inserts a null
character into the output stream. It typically works
with std::ostrstream, when the associated output
buffer needs to be null-terminated to be processed as
a C string.
• flush: It is also defined in ostream and it flushes the
output stream, i.e. it forces all the output written on
the screen or in the file. Without flush, the output
would be the same, but may not appear in real-
time. Examples:
• CPP

#include <iostream>

#include <istream>

#include <sstream>

#include <string>

using namespace std;

int main()

istringstream str(" Programmer");

string line;

// Ignore all the whitespace in string

// str before the first word.

getline(str >> std::ws, line);


// you can also write str>>ws

// After printing the output it will automatically

// write a new line in the output stream.

cout << line << endl;

// without flush, the output will be the same.

cout << "only a test" << flush;

// Use of ends Manipulator

cout << "\na";

// NULL character will be added in the Output

cout << "b" << ends;

cout << "c" << endl;

return 0;

Output:
Programmer
only a test
abc
Ques-what are different types of constructors in c++?
--Constructor in C++ is a special method that is invoked automatically
at the time of object creation. It is used to initialize the data members of
new objects generally. The constructor in C++ has the same name as
the class or structure. It constructs the values i.e. provides data for the
object which is why it is known as constructor.
• Constructor is a member function of a class, whose name is same as
the class name.
• Constructor is a special type of member function that is used to
initialize the data members for an object of a class automatically, when
an object of the same class is created.
• Constructor is invoked at the time of object creation. It constructs the
values i.e. provides data for the object that is why it is known as
constructor.
• Constructor do not return value, hence they do not have a return
type.

The prototype of the constructor looks like


<class-name> (list-of-parameters);

Constructor can be defined inside the class declaration or outside


the class declaration
a. Syntax for defining the constructor within the class
<class-name>(list-of-parameters)
{
//constructor definition
}
b. Syntax for defining the constructor outside the class
<class-name>: :<class-name>(list-of-parameters)
{
//constructor definition
}
#include<iostream>
using namespace std;
class student
{
int rno;
char name[50];
double fee;
public:
student()
{
cout<<"Enter the RollNo:";
cin>>rno;
cout<<"Enter the Name:";
cin>>name;
cout<<"Enter the Fee:";
cin>>fee;
}

void display()
{
cout<<endl<<rno<<"\t"<<name<<"\t"<<fee;
}
};

int main()
{
student s; //constructor gets called automatically when we create
the object of the class
s.display();
return 0;

}
Characteristics of constructor
• The name of the constructor is same as its class name.
• Constructors are mostly declared in the public section of the
class though it can be declared in the private section of the
class.
• Constructors do not return values; hence they do not have a
return type.
• A constructor gets called automatically when we create the
object of the class.
• Constructors can be overloaded.
• Constructor can not be declared virtual.

Types of constructor
• Default constructor
• Parameterized constructor
• Overloaded constructor
• Constructor with default value
• Copy constructor
• Inline constructor

Constructor does not have a return value, hence they do not have a
return type.
The prototype of Constructors is as follows:
<class-name> (list-of-parameters);

Constructors can be defined inside or outside the class declaration:-


The syntax for defining the constructor within the class:
<class-name> (list-of-parameters) { // constructor definition }

The syntax for defining the constructor outside the class:


<class-name>: :<class-name> (list-of-parameters){ // constructor
definition}
Ques-explain various ios class function and flags used for formatting console i/o in c++?
1. --ios class functions and flags.

2. Manipulators.

3. User-defined output functions.

1. ios Class functions and flags


The ios class contains a large number of member functions that could be used to
format the output in a number of ways. The most important ones among them are
listed below.

Function Syntax Use

To specify the required field size for


width() cout.width(size);
displaying an output value.

To specify the number of digits to be


precision() cout.precision(2); displayed after the decimal point of a float
value.

To specify a character that is used to fill


fill() cout.fill(‘character’);
the unused portion of a field.

To specify format flags that can control


cout.setf(arg1,
setf() the form of output display such as left or
arg2);
right justification.
unsetf() cout.resetiosflags() To clear the flags specified.

Formatted IO Functions
In setf() function we can provide one or two argument.

cout.setf(arg1, arg2);

2. Manipulators
Manipulators are used to manipulate the output in specific format. Below is the list
of manipulators in c++.

Manipulators Use

To specify the required field size for displaying an output


setw()
value.

To specify the number of digits to be displayed after the


setprecision()
decimal point of a float value.

To specify a character that is used to fill the unused portion of


setfill()
a field.

To specify format flags that can control the form of output


setiosflags()
display such as left or right justification.

resetiosflags() To clear the flags specified.

Ques-what is copy constructor?


--A copy constructor is a member function that initializes an object
using another object of the same class. In simple terms, a constructor
which creates an object by initializing it with an object of the same
class, which has been created previously is known as a copy
constructor.
Copy constructor is used to initialize the members of a newly created
object by copying the members of an already existing object.

Copy constructor takes a reference to an object of the same class as an


argument.
Sample(Sample &t)
{
id=t.id;
}

The process of initializing members of an object through a copy


constructor is known as copy initialization.

It is also called member-wise initialization because the copy


constructor initializes one object with the existing object, both
belonging to the same class on a member by member copy basis.

The copy constructor can be defined explicitly by the programmer. If


the programmer does not define the copy constructor, the compiler
does it for us.

#include<iostream>
#include<string.h>
using namespace std;
class student
{
int rno;
char name[50];
double fee;
public:
student(int,char[],double);
student(student &t) //copy constructor
{
rno=t.rno;
strcpy(name,t.name);
fee=t.fee;
}
void display();

};

student::student(int no,char n[],double f)


{
rno=no;
strcpy(name,n);
fee=f;
}

void student::display()
{
cout<<endl<<rno<<"\t"<<name<<"\t"<<fee;
}

int main()
{
student s(1001,"Manjeet",10000);
s.display();

student manjeet(s); //copy constructor called


manjeet.display();

return 0;
2. Parameterized Constructors: It is possible to pass arguments to
constructors. Typically, these arguments help initialize an object when
it is created. To create a parameterized constructor, simply add
parameters to it the way you would to any other function. When you
define the constructor’s body, use the parameters to initialize the
object.
Note: when the parameterized constructor is defined and no default
constructor is defined explicitly, the compiler will not implicitly call the
default constructor and hence creating a simple object as
Student s;
Will flash an error

• CPP

// CPP program to illustrate


// parameterized constructors
#include <iostream>
using namespace std;

class Point {
private:
int x, y;

public:
// Parameterized Constructor
Point(int x1, int y1)
{
x = x1;
y = y1;
}

int getX() { return x; }


int getY() { return y; }
};

int main()
{
// Constructor called
Point p1(10, 15);

// Access values assigned by constructor


cout << "p1.x = " << p1.getX()
<< ", p1.y = " << p1.getY();

return 0;
}

Output
p1.x = 10, p1.y = 15

You might also like