Вы находитесь на странице: 1из 30

Object oriented programming with C++ 16CSE43

Module 2
Introduction to classes and Objects 9hrs

Constructors and Destructors


Constructors are special class member functions which performs initialization of every object. The
Compiler calls the Constructor whenever an object is created. Constructors initialize values to object
members after storage is allocated to the object.
Constructors will have name same as class name without any return type.
class A
{
int x;
public:
A(); //Constructor
};

Constructors can be defined either inside the class definition or outside class definition using class
name and scope resolution :: operator.

class A
{
int i;
public:
A(); //Constructor declared
};

A::A() // Constructor definition


{
i=1;
}
Muralidhara S, AP, Dept.of CSE
Object oriented programming with C++ 16CSE43

Types of Constructors
Constructors are of three types:
Default Constructor
Parametrized Constructor
Copy Constructor

Default Constructor
Default constructor is the constructor which doesn't take any argument. It has no parameter.
Syntax :
class_name ()
{ classname(){ //Constructor Definition } };

Example :
class Cube
{
int side;
public:
Cube()
{
side=10;
}
};
int main()
{
Cube c;
cout << c.side;
return 0;
}
Output : 10

Muralidhara S, AP, Dept.of CSE


Object oriented programming with C++ 16CSE43

In this case, as soon as the object is created the constructor is called which initializes its data
members.

A default constructor is so important for initialization of object members, that even if we do not define
a constructor explicitly, the compiler will provide a default constructor implicitly.

class Cube
{
int side;
};

int main()
{
Cube c;
cout << c.side;
return 0;
}
Output : 0
In this case, default constructor provided by the compiler will be called which will initialize the object
data members to default value, that will be 0 in this case.

Parameterized Constructor
These are the constructors with parameter. Using this Constructor you can provide different values to
data members of different objects, by passing the appropriate values as argument.

Example:

class Cube
{
int side;

Muralidhara S, AP, Dept.of CSE


Object oriented programming with C++ 16CSE43

public:
Cube(int x)
{
side=x;
}
};

int main()
{
Cube c1(10);
Cube c2(20);
Cube c3(30);
cout << c1.side;
cout << c2.side;
cout << c3.side;
return 0;
}
OUTPUT : 10 20 30

By using parameterized constructor in above case, we have initialized 3 objects with user defined
values. We can have any number of parameters in a constructor.

Copy Constructor

These are special type of Constructors which takes an object as argument, and is used to copy values
of data members of one object into other object.
Syntax
class_name ( const class_name & ) {
// body of constructor
}

Muralidhara S, AP, Dept.of CSE


Object oriented programming with C++ 16CSE43

Example
#include<iostream>
using namespace std;

class Point
{
private:
int x, y;
public:
Point(int x1, int y1) { x = x1;
y = y1; }

// Copy constructor
Point(const Point &p2) {
x = p2.x;
y = p2.y; }

int getX() { return x; }


int getY() { return y; }
};

int main()
{
Point p1(10, 15); // Normal constructor is called here
Muralidhara S, AP, Dept.of CSE
Object oriented programming with C++ 16CSE43

Point p2 = p1; // Copy constructor is called here

// Let us access values assigned by constructors


cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
cout << "\np2.x = " << p2.getX() << ", p2.y = " << p2.getY();
return 0;
}

Constructor Overloading
Just like other member functions, constructors can also be overloaded. In fact when you have both
default and parameterized constructors defined in your class you are having Overloaded
Constructors, one with no parameter and other with parameter.

You can have any number of Constructors in a class that differ in parameter list.

class Student
{
int rollno;
string name;
public:
Student(int x)
{
rollno=x;
name="None";
}
Student(int x, string str)
{
rollno=x ;
name=str ;
}

Muralidhara S, AP, Dept.of CSE


Object oriented programming with C++ 16CSE43

};

int main()
{
Student A(10);
Student B(11,"Ram");
}
In above case we have defined two constructors with different parameters, hence overloading the
constructors.

One more important thing, if you define any constructor explicitly, then the compiler will not provide
default constructor and you will have to define it yourself.

In the above case if we write Student S;


in main(), it will lead to a compile time error, because we haven't defined default constructor, and
compiler will not provide its default constructor because we have defined other parameterized
constructors.

Destructors
Destructor is a special class function which destroys the object as soon as the scope of object ends.
The destructor is called automatically by the compiler when the object goes out of scope.
The syntax for destructor is same as that for the constructor, the class name is used for the name of
destructor, with a tilde ~ sign as prefix to it.

class A
{
public:
~A();
};

Destructors will never have any arguments.

Muralidhara S, AP, Dept.of CSE


Object oriented programming with C++ 16CSE43

Example to see how Constructor and Destructor is called

class A
{
A()
{
cout << "Constructor called";
}

~A()
{
cout << "Destructor called";
}
};

int main()
{
A obj1; // Constructor Called
int x=1
if(x)
{
A obj2; // Constructor Called
} // Destructor Called for obj2
} // Destructor called for obj1

Single Definition for both Default and Parameterized Constructor


In this example we will use default argument to have a single definition for both default and
parameterized constructor.

Muralidhara S, AP, Dept.of CSE


Object oriented programming with C++ 16CSE43

class Dual
{
int a;
public:
Dual(int x=0) // default arguments
{
a=x;
}
};

int main()
{
Dual obj1;
Dual obj2(10);
}
Here, in this program, a single Constructor definition will take care for both these object
initializations. We don't need separate default and parameterized constructors.

Pointers in C++
Pointer variable hold the address of another variable.
Example:
#include <iostream>
using namespace std;
int main ()
{
int var1;
char var2[10];
cout << "Address of var1 variable: ";

Muralidhara S, AP, Dept.of CSE


Object oriented programming with C++ 16CSE43

cout << &var1 << endl;


cout << "Address of var2 variable: ";
cout << &var2 << endl;
return 0;
}
When the above code is compiled and executed, it produces result something as follows:
Address of var1 variable: 0xbfebd5c0
Address of var2 variable: 0xbfebd5b6
A pointer is a variable whose value is the address of another variable. Like any variable or constant,
you must declare a pointer before you can work with it.

The general form of a pointer variable declaration is:


type *var-name;

Here, type is the pointer's base type; it must be a valid C++ type and var-name is the name of the
pointer variable. The asterisk you used to declare a pointer is the same asterisk that you use for
multiplication.
However, in this statement the asterisk is being used to designate a variable as a pointer.
Following are the valid pointer declaration:
int *ip; // pointer to an integer
double *dp; // pointer to a double
float *fp; // pointer to a float
char *ch // pointer to character

Example:

#include <iostream>
using namespace std;
int main ()

Muralidhara S, AP, Dept.of CSE


Object oriented programming with C++ 16CSE43

{
int var = 20; // actual variable declaration.
int *ip; // pointer variable
ip = &var; // store address of var in pointer variable
cout << "Value of var variable: ";
cout << var << endl;
// print the address stored in ip pointer variable
cout << "Address stored in ip variable: ";
cout << ip << endl;
// access the value at the address available in pointer
cout << "Value of *ip variable: ";
cout << *ip << endl;
return 0;
}
When the above code is compiled and executed, it produces result something as follows:
Value of var variable: 20
Address stored in ip variable: 0xbfc601ac
Value of *ip variable: 20

Pointers to class members


Just like pointers to normal variables and functions, we can have pointers to class member functions
and member variables.

We can define pointer of class type, which can be used to point to class objects.
class Simple
{
public:
int a;
};

Muralidhara S, AP, Dept.of CSE


Object oriented programming with C++ 16CSE43

int main()
{
Simple obj;
Simple* ptr; // Pointer of class type
ptr = &obj;

cout << obj.a;


cout << ptr->a; // Accessing member with pointer
}
Here you can see that we have declared a pointer of class type which points to class's object. We can
access data members and member functions using pointer name with arrow -> symbol.

Pointer to Data Members of class


We can use pointer to point to class's data members (Member variables).

Syntax for Declaration:

datatype class_name :: *pointer_name ;

Syntax for Assignment:

pointer_name = &class_name :: datamember_name ;

Both declaration and assignment can be done in a single statement too.

datatype class_name::*pointer_name = &class_name::datamember_name ;

Muralidhara S, AP, Dept.of CSE


Object oriented programming with C++ 16CSE43

Using with Objects

For accessing normal data members we use the dot . operator with object and -> with pointer to
object.
But when we have a pointer to data member, we have to dereference that pointer to get what it’s
pointing to, hence it becomes,
Object.*pointerToMember
and with pointer to object, it can be accessed by writing,
ObjectPointer->*pointerToMember

Example

class Data
{
public:
int a;
void print() { cout << "a is "<< a; }
};

int main()
{
Data d, *dp;
dp = &d; // pointer to object

int Data::*ptr=&Data::a; // pointer to data member 'a'

d.*ptr=10;
d.print();

dp->*ptr=20;

Muralidhara S, AP, Dept.of CSE


Object oriented programming with C++ 16CSE43

dp->print();
}
Output :
a is 10 a is 20

The syntax is very tough, hence they are only used under special circumstances.

Pointer to Member Functions


Pointers can be used to point to class's Member functions.

Syntax :
return_type (class_name::*ptr_name) (argument_type) = &class_name::function_name ;

Below is an example to show how we use pointer to member functions.

class Data
{
public:
int f (float) { return 1; }
};

int (Data::*fp1) (float) = &Data::f; // Declaration and assignment


int (Data::*fp2) (float); // Only Declaration

int main()
{
fp2 = &Data::f; // Assignment inside main()

Muralidhara S, AP, Dept.of CSE


Object oriented programming with C++ 16CSE43

Calling an ordinary function using a pointer to ordinary function:


result = pointer_name(arguments); // short form, allowed
or
result = (*pointer_name)(arguments); // the more verbose form
Calling the member function on an object using a pointer-to-member-function
result = (object.*pointer_name)(arguments);
or calling with a pointer to the object
result = (object_ptr->*pointer_name)(arguments);

Structures vs Classes

In C++, a structure is same as class except the following differences:

1) Members of a class are private by default and members of struct are public by default.

For example program 1 fails in compilation and program 2 works fine.


// Program 1
#include <iostream>

class Test {
int x; // x is private
};
int main()
{
Test t;
t.x = 20; // compiler error because x is private
getchar();
return 0;
}

Muralidhara S, AP, Dept.of CSE


Object oriented programming with C++ 16CSE43

// Program 2
#include <iostream>

struct Test {
int x; // x is public
};
int main()
{
Test t;
t.x = 20; // works fine because x is public
getchar();
return 0;
}

2) When deriving a struct from a class/struct, default access-specifier for a base class/struct is public.
And when deriving a class, default access specifier is private. (Inheritance will be discussed later)
For example program 3 fails in compilation and program 4 works fine.
// Program 3
#include <stdio.h>

class Base {
public:
int x;
};

class Derived : Base { }; // is equilalent to class Derived : private Base {}

int main()
{

Muralidhara S, AP, Dept.of CSE


Object oriented programming with C++ 16CSE43

Derived d;
d.x = 20; // compiler error becuase inheritance is private
getchar();
return 0;
}

// Program 4
#include <stdio.h>

class Base {
public:
int x;
};

struct Derived : Base { }; // is equilalent to struct Derived : public Base {}

int main()
{
Derived d;
d.x = 20; // works fine becuase inheritance is public
getchar();
return 0;
}

C++ Dynamic Memory


Memory in your C++ program is divided into two parts:

The stack: All variables declared inside the function will take up memory from the stack.

Muralidhara S, AP, Dept.of CSE


Object oriented programming with C++ 16CSE43

The heap: This is unused memory of the program and can be used to allocate the memory
dynamically when program runs.

The new and delete operators


There is following generic syntax to use new operator to allocate memory dynamically for any data-
type.
new data-type;
Here, data-type could be any built-in data type including an array or any user defined data types
include class or structure. Let us start with built-in data types. For example we can define a pointer to
type double and then request that the memory be allocated at execution time. We can do this using
the new operator with the following statements:

double* pvalue = NULL; // Pointer initialized with null


pvalue = new double; // Request memory for the variable
The memory may not have been allocated successfully, if the free store had been used up. So it is good
practice to check if new operator is returning NULL pointer and take appropriate action as below:

double* pvalue = NULL;


if( !(pvalue = new double )) {
cout << "Error: out of memory." <<endl;
exit(1);
}

delete pvalue; // Release memory pointed to by pvalue

Example:

#include <iostream>
using namespace std;

int main () {

Muralidhara S, AP, Dept.of CSE


Object oriented programming with C++ 16CSE43

double* pvalue = NULL; // Pointer initialized with null


pvalue = new double; // Request memory for the variable

*pvalue = 29494.99; // Store value at allocated address


cout << "Value of pvalue : " << *pvalue << endl;

delete pvalue; // free up the memory.

return 0;
}
If we compile and run above code, this would produce the following result:

Value of pvalue : 29495

Dynamic Memory Allocation for Arrays

Consider you want to allocate memory for an array of characters, i.e., string of 20 characters. Using
the same syntax what we have used above we can allocate memory dynamically as shown below.

char* pvalue = NULL; // Pointer initialized with null


pvalue = new char[20]; // Request memory for the variable
To remove the array that we have just created the statement would look like this:

delete [] pvalue; // Delete array pointed to by pvalue

Following is the syntax of new operator for a multi-dimensional array as follows:

int ROW = 2;

Muralidhara S, AP, Dept.of CSE


Object oriented programming with C++ 16CSE43

int COL = 3;
double **pvalue = new double* [ROW]; // Allocate memory for rows

// Now allocate memory for columns


for(int i = 0; i < ROW; i++) {
pvalue[i] = new double[COL];
}
The syntax to release the memory for multi-dimensional will be as follows:

for(int i = 0; i < ROW; i++) {


delete[] pvalue[i];
}
delete [] pvalue;

Dynamic Memory Allocation for Objects


Objects are no different from simple data types. For example, consider the following code where we
are going to use an array of objects to clarify the concept:

#include <iostream>
using namespace std;
class Box {
public:
Box() {
cout << "Constructor called!" <<endl;
}
~Box() {
cout << "Destructor called!" <<endl;
}
};

Muralidhara S, AP, Dept.of CSE


Object oriented programming with C++ 16CSE43

int main( ) {
Box* myBoxArray = new Box[4];

delete [] myBoxArray; // Delete array

return 0;
}
If you were to allocate an array of four Box objects, the Simple constructor would be called four times
and similarly while deleting these objects, destructor will also be called same number of times.
If we compile and run above code, this would produce the following result:

Constructor called!
Constructor called!
Constructor called!
Constructor called!
Destructor called!
Destructor called!
Destructor called!
Destructor called!

Local Classes
A class declared inside a function becomes local to that function and is called Local Class in C++.
For example, in the following program, Test is a local class in fun().

#include<iostream>
using namespace std;

void fun()

Muralidhara S, AP, Dept.of CSE


Object oriented programming with C++ 16CSE43

{
class Test // local to fun
{
/* members of Test class */
};
}

int main()
{
return 0;
}

Following are some interesting facts about local classes.


1) A local class type name can only be used in the enclosing function.
For example, in the following program, declarations of t and tp are valid in fun(), but invalid in main().

#include<iostream>
using namespace std;

void fun()
{
// Local class
class Test
{
/* ... */
};

Test t; // Fine
Test *tp; // Fine

Muralidhara S, AP, Dept.of CSE


Object oriented programming with C++ 16CSE43

int main()
{
Test t; // Error
Test *tp; // Error
return 0;
}

2) All the methods of Local classes must be defined inside the class only. For example, program 1
works fine and program 2 fails in compilation.

// PROGRAM 1
#include<iostream>
using namespace std;

void fun()
{
class Test // local to fun
{
public:

// Fine as the method is defined inside the local class


void method() {
cout << "Local Class method() called";
}
};
Test t;
t.method();

Muralidhara S, AP, Dept.of CSE


Object oriented programming with C++ 16CSE43

int main()
{
fun();
return 0;
}

Output:

Local Class method() called

// PROGRAM 2
#include<iostream>
using namespace std;

void fun()
{
class Test // local to fun
{
public:
void method();
};

// Error as the method is defined outside the local class


void Test::method()
{
cout << "Local Class method()";
}

Muralidhara S, AP, Dept.of CSE


Object oriented programming with C++ 16CSE43

int main()
{
return 0;
}
Output:

Compiler Error:
In function 'void fun()':
error: a function-definition is not allowed here before '{' token

3) A Local class cannot contain static data members. It may contain static functions though. For
example, program 1 fails in compilation, but program 2 works fine.

// PROGRAM 1
#include<iostream>
using namespace std;

void fun()
{
class Test // local to fun
{
static int i;
};
}

int main()
{

Muralidhara S, AP, Dept.of CSE


Object oriented programming with C++ 16CSE43

return 0;
}

Compiler Error:
In function 'void fun()':
error: local class 'class fun()::Test' shall not have static data member 'int fun()::Test::i'

// PROGRAM 2
#include<iostream>
using namespace std;

void fun()
{
class Test // local to fun
{
public:
static void method()
{
cout << "Local Class method() called";
}
};

Test::method();
}

int main()
{
fun();
return 0;

Muralidhara S, AP, Dept.of CSE


Object oriented programming with C++ 16CSE43

Output:

Local Class method() called

4) Member methods of local class can only access static and enum variables of the enclosing function.
Non-static variables of the enclosing function are not accessible inside local classes. For example, the
program 1 compiles and runs fine. But, program 2 fails in compilation.

// PROGRAM 1
#include<iostream>
using namespace std;

void fun()
{
static int x;
enum {i = 1, j = 2};

// Local class
class Test
{
public:
void method() {
cout << "x = " << x << endl; // fine as x is static
cout << "i = " << i << endl; // fine as i is enum
}
};

Test t;

Muralidhara S, AP, Dept.of CSE


Object oriented programming with C++ 16CSE43

t.method();
}

int main()
{
fun();
return 0;
}

Output:

x=0
i=1

// PROGRAM 2
#include<iostream>
using namespace std;

void fun()
{
int x;

// Local class
class Test
{
public:
void method() {
cout << "x = " << x << endl;
}

Muralidhara S, AP, Dept.of CSE


Object oriented programming with C++ 16CSE43

};

Test t;
t.method();
}

int main()
{
fun();
return 0;
}

Output:

In member function 'void fun()::Test::method()':


error: use of 'auto' variable from containing function

5) Local classes can access global types, variables and functions. Also, local classes can access other
local classes of same function.. For example, following program works fine.

#include<iostream>
using namespace std;

int x;

void fun()
{

// First Local class

Muralidhara S, AP, Dept.of CSE


Object oriented programming with C++ 16CSE43

class Test1 {
public:
Test1() { cout << "Test1::Test1()" << endl; }
};

// Second Local class


class Test2
{
// Fine: A local class can use other local classes of same function
Test1 t1;
public:
void method() {
// Fine: Local class member methods can access global variables.
cout << "x = " << x << endl;
}
};

Test2 t;
t.method();
}

int main()
{
fun();
return 0;
}
Output:
Test1::Test1()
x=0

Muralidhara S, AP, Dept.of CSE

Вам также может понравиться