DAY 2 Class MemberFunction Constructor

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 35

School of Computing Science and Engineering

Course Code: Course Name: Data structures using C++

Day-2:
Basic I/O, Class and objects, Class member
functions, Class access modifiers;
Constructor and destructor, Dynamic Constructor

Faculty Name: Dr. Dileep K Yadav Program Name: B.Tech


Basic I/O

C++ IO are based on streams, which are


sequence of bytes flowing in and out of the
programs (just like water and oil flowing
through a pipe). In input operations, data
bytes flow from an input source (such as
keyboard, file, network or another program)
into the program.
Basic I/O
I/O Library Header

There are following header files important to C++ programs −

Sr. No Header File & Function and Description


1 <iostream>
This file defines the cin, cout, cerr and clog objects, which correspond to the standard input stream,
the standard output stream, the un-buffered standard error stream and the buffered standard error
stream, respectively.

2 <iomanip>
This file declares services useful for performing formatted I/O with so-called parameterized stream
manipulators, such as setw and setprecision.
3 <fstream>
This file declares services for user-controlled file processing. We will discuss about it in detail in File
and Stream related chapter.
I/O Examples:
Input Stream:
Output Stream:
The predefined object cin is an instance of istream class.
The predefined object cout is an instance
The cin object is said to be attached to the standard input
of ostream class. The cout object is said to be "connected
device, which usually is the keyboard. The cin is used in
to" the standard output device, which usually is the display
conjunction with the stream extraction operator, which is
screen. The cout is used in conjunction with the stream
written as >> which are two greater than signs as shown in
insertion operator, which is written as << which are two less
the following example.
than signs as shown in the following example.
#include <iostream>
using namespace std;
#include <iostream>
int main(){
using namespace std;
char name[50];
cout << "Please enter your name: "; cin >>
int main() { name;
char str[] = "Hello C++"; cout << "Your name is: " << name << endl;
cout << "Value of str is : " << str << endl; }
}
When the above code is compiled and executed, it will prompt
When the above code is compiled and executed, it you to enter a name.
produces the following result − Please enter your name: cplusplus
Value of str is : Hello C++ Your name is: cplusplus
I/O Examples:

Standard Error Stream (cerr):


• The predefined object cerr is an instance of ostream class. The cerr object is said
to be attached to the standard error device, which is also a display screen but the
object cerr is un-buffered and each stream insertion to cerr causes its output to
appear immediately.
#include <iostream>
using namespace std;

int main() {
char str[] = "Unable to read....";
cerr << "Error message : " << str << endl;
I/O Examples:

Standard Log Stream (clog)


• The predefined object clog is an instance of ostream class. The clog object is said
to be attached to the standard error device, which is also a display screen but the
object clog is buffered. This means that each insertion to clog could cause its
output to be held in a buffer until the buffer is filled or until the buffer is flushed.
#include <iostream>
using namespace std;

int main() {
char str[] = "Unable to read....";
clog << "Error message : " << str << endl;
C++ Classes/Objects

• C++ is an object-oriented programming language.


• Everything in C++ is associated with classes and objects, along with its
attributes and methods. For example: in real life, a car is an object.
The car has attributes, such as weight and color, and methods, such
as drive and brake.
• Attributes and methods are basically variables and functions that
belongs to the class. These are often referred to as "class members".
• A class is a user-defined data type that we can use in our program,
and it works as an object constructor, or a "blueprint" for creating
objects.
C++ Classes/Objects
• C++ is an object-oriented programming language.
• Everything in C++ is associated with classes and objects, along with its
attributes and methods. For example: in real life, a car is an object.
The car has attributes, such as weight and color, and methods, such
as drive and brake.
• Attributes and methods are basically variables and functions that
belongs to the class. These are often referred to as "class members".
• A class is a user-defined data type that we can use in our program,
and it works as an object constructor, or a "blueprint" for creating
objects.
Difference between Class and Object in C++
Create a Class in C++

• Create a class in C++: Use keyword “class”.

class MyClass { // The class


public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};

Explaination:

•The class keyword is used to create a class called MyClass.


•The public keyword is an access specifier, which specifies that members (attributes and methods) of the
class are accessible from outside the class. You will learn more about access specifiers later.
•Inside the class, there is an integer variable myNum and a string variable myString. When variables are
declared within a class, they are called attributes.
•At last, end the class definition with a semicolon ;
Representation of Class in C++
Object in C++
Create an Object

In C++, an object is created from a class.


We have already created the class named MyClass, so now we can use this to create objects.
To create an object of MyClass, specify the class name, followed by the object name.
To access the class attributes (myNum and myString), use the dot syntax (.) on the object:
int main() {
// Create an object of MyClass
class MyClass { // The class MyClass myObj;
public: // Access specifier
int myNum; // Attribute (int variable) // Access attributes and set values
string myString; // Attribute myObj.myNum = 15;
(string variable) myObj.myString = "Some Text";
};
// Print attribute values
cout << myObj.myNum << "\n";
cout << myObj.myString;
return 0; Output:
} 15
Some Text
Representation of Object in C++
Member Functions

• A member function of a class is a function that has its definition or its prototype within the class definition like any
other variable.
• It operates on any object of the class of which it is a member, and has access to all the members of a class for that
object.

Let us take previously defined class to access the members of the class using a member function instead of directly
accessing them −

class Box
{
public: double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
double getVolume(void); // Returns box volume
};
Member Functions

Member functions can be defined within the class definition or separately using scope resolution operator, : −.
Defining a member function within the class definition declares the function inline, even if you do not use the inline
specifier. So either you can define Volume() function as below
class Box
{
public: double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
double getVolume(void); // Returns box volume

double getVolume(void){
return length * breath * height
}

};
Member Functions

you can define the same function outside the class using the scope resolution operator (::) as follows

class Box
{
public: double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
double getVolume(void); // Returns box volume

double Box:: getVolume(void){


return length * breath * height
}

};

Here, only important point is that you would have to use class name just before :: operator.
Object and Function Calling
A member function will be called using a dot operator (.) on a object where it will manipulate data related to that object only as
follows −

Box myBox; // Create an Object


myBox.getVolume() // Call member function for an object
Overview
The main purpose of C++ programming is to add object orientation to the C programming language and classes are
the central feature of C++ that supports object-oriented programming and are often called user-defined types.

A class is used to specify the form of an object and it combines data representation and methods for manipulating that
data into one neat package. The data and functions within a class are called members of the class.

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

Let us take previously defined class to access the members of the class using a member function instead of directly accessing them −

class Box
{
public: // keyword public determines the access attributes of the members of the class that follows it.
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
• 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

Both of the objects Box1 and Box2 will have their own copy of data members.
Accessing the Data Members

• The public data members of objects of a class can be accessed using the direct member access operator (.).
Let us try the following example to make the things clear −
#include<iostream>

class Box
{
public: // keyword public determines the access attributes of the members of the class that follows it.
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
// box 1 specification
int main() { Box1.height = 5.0;
Box Box1; // Declare Box1 of type Box Box1.length = 6.0;
Box Box2; // Declare Box2 of type Box Box1.breadth = 7.0;
double volume = 0.0; // Store the volume of a box here
Accessing the Data Members
// box 2 specification
Box2.height = 10.0;
Box2.length = 12.0;
Box2.breadth = 13.0; // volume of box 1
volume = Box1.height * Box1.length * Box1.breadth;
cout << "Volume of Box1 : " << volume <<endl; // volume of box 2
volume = Box2.height * Box2.length * Box2.breadth;
cout << "Volume of Box2 : " << volume <<endl;
return 0;

}
Output:
Volume of Box1 : 210
Volume of Box2 : 1560
Class Access Modifiers in C++

• There are 3 types of access modifiers available in C++:


• Public
• Private
• Protected
Class Access Modifiers in C++
Various Definitions…
Sr. No Concept & Description
1 Class Member Functions A member function of a class is a function that has its definition or its prototype within
the class definition like any other variable.
2 Class Access Modifiers A class member can be defined as public, private or protected. By default members would
be assumed as private.
3 Constructor & Destructor A class constructor is a special function in a class that is called when a new object of the
class is created. A destructor is also a special function which is called when created object is deleted.

4 Copy Constructor The copy constructor is a constructor which creates an object by initializing it with an object of
the same class, which has been created previously.
5 Friend Functions A friend function is permitted full access to private and protected members of a class.
6 Inline Functions With an inline function, the compiler tries to expand the code in the body of the function in place
of a call to the function.
7 this Pointer Every object has a special pointer this which points to the object itself.
8 Pointer to C++ Classes A pointer to a class is done exactly the same way a pointer to a structure is. In fact a class is
really just a structure with functions in it.
9 Static Members of a Class Both data members and function members of a class can be declared as static.
Constructor

Constructor:
A constructor is a member function of a class which initializes objects of a class. In C++, Constructor is
automatically called when object(instance of class) create. It is special member function of the class.
• The Compiler calls the Constructor whenever an object is created.
• It is special member function of the class.
• Constructors initialize values to object members after storage is allocated to the object.
• Compiler identifies a given member function is a constructor by its name and the return type.
• Constructors are always public.
Difference between constructor and member function
•Constructor name must be same as class name but functions cannot have same name as class name.
•Constructors does not have return type whereas functions must have return type.
•Constructors is automatically called when an object is created.
•Member function can be virtual, but there is no concept of virtual constructors.
•Constructors are invoked at the time of object creation automatically and cannot be called explicitly using class
objects.
Constructor
Constructor

// Cpp program to illustrate the concept of Constructors


#include <iostream>
Default Constructor in C++ using namespace std;
•Default constructor is the constructor which doesn’t take any class construct
argument. It has no parameters. {
•In this case, as soon as the object is created the constructor is public:
called which initializes its data members. int a, b;
•A default constructor is so important for initialization of object construct() // Default Constructor
members, that even if we do not define a constructor explicitly, {
a = 10;
the compiler will provide a default constructor implicitly.
b = 20;
}
};

int main()
{ // Default constructor called automatically when the object is
created
construct c;
cout << "a: " << c.a << endl
<< "b: " << c.b;
return 1;
}
Constructor

Parameterized Constructor in C++:


•Arguments can be passed to parameterized constructor.
•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
// parameterized constructors
other function.
#include <iostream> •When you define the constructor’s body, use the parameters to initialize the object.
using namespace std; we can also have more than one constructor in a class and that concept is called constructor
overloading.
class Point{
private: int main()
int x, y; {
public: // Parameterized Constructor // Constructor called
Point(int x1, int y1) Point p1(10, 15);
{
x = x1; // Access values assigned by constructor
y = y1; cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
}
int getX() { return x; } return 0;
int getY() { return y; } }
};
Constructor

#include "iostream"
Copy Constructor in C++ using namespace std;
•A copy constructor is a member function which initializes an object using class point{
another object of the same class. private:
•Whenever we define one or more non-default constructors( with
double x, y;
parameters ) for a class, a default constructor( without parameters ) should
public: // Non-default Constructor & default Constructor
also be explicitly defined as the compiler will not provide a default
constructor in this case. point (double px, double py)
•An object can be initialized with another object of same type. This is same {
as copying the contents of a class to another class. x = px, y = py;
}
};
int main(void)
{// Define an array of size 10 & of type point. This line will
cause error
point a[10];

// Remove above line and program will compile without


error
point b = point(5, 6);
}
Destructor
Destructor:
Destructor is a member function which destructs or deletes an object.

Syntax:
~constructor-name();

Properties of Destructor:
•Destructor function is automatically invoked when the objects are destroyed.
•It cannot be declared static or const.
•The destructor does not have arguments.
•It has no return type not even void.
•An object of a class with a Destructor cannot become a member of the union.
•A destructor should be declared in the public section of the class.
•The programmer cannot access the address of destructor.
Destructor

When is destructor called?


A destructor function is called automatically when the object goes out of scope:
(1) the function ends
(2) the program ends
(3) a block containing local variables ends
(4) a delete operator is called

How destructors are different from a normal member function?


Destructors have same name as the class preceded by a tilde (~)
Destructors don’t take any argument and don’t return anything
Destructor
class String {
private:
char* s;
int size;

public:
String(char*); // constructor
~String(); // destructor
};

String::String(char* c)
{
size = strlen(c);
s = new char[size + 1];
strcpy(s, c);
}
String::~String() { delete[] s; }
Thank You

You might also like