0% found this document useful (0 votes)
24 views30 pages

Chapter 2

Uploaded by

Vinayak Kapoor
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)
24 views30 pages

Chapter 2

Uploaded by

Vinayak Kapoor
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/ 30

Chapter 2

Classes and Object


C STRUCTURES REVISITED
• What is a structure?
A structure is a user defined data type in C/C++. A structure creates a data type that can
be used to group items of possibly different types into a single name.
Example: Struct Keyword tag or structure tag

struct Person
{ char name[10]; Members or Fields of structure
int age;
float salary;
}
How to create a structure?
‘struct’ keyword is used to create a structure.
How to declare structure variables?

A structure variable can either be declared with structure declaration or as a separate declaration like
basic types.

Eg:- Person bill

// A variable declaration with structure declaration. // A variable declaration like basic data types
struct Point
{ struct Point
int x, y; { int x, y;
} p1; // The variable p1 is declared with 'Point’ };
int main()
{
struct Point p1; // The variable p1 is declared like a
normal variable
}
How to access structure elements?
Structure members are accessed using dot (.) operator.

#include<iostream>

struct Point
{
int x, y;
};

int main()
{
struct Point p1 = {0, 1};

// Accessing members of point p1


p1.x = 20;
cout<<p1.x<<“\n”<<p1.y;

return 0;
}
Limitations of C Structures
The C structure does not allow the struct data type to be treated like built-in data types
We cannot use operators like +,- etc. on Structure variables. For example, consider the following code:
struct number
{
float x;
};
int main()
{
struct number n1,n2,n3;
n1.x=4;
n2.x=3;
n3=n1+n2;
return 0;
}

/*Output:

prog.c: In function 'main':


prog.c:10:7: error:
invalid operands to binary + (have 'struct number' and 'struct number')
n3=n1+n2;

*/
Limitation…..
Extension to Structure
• C++ define all the features of structure as defined in C.
• C++ add the concept of OOP.
• In C++, a structure can have both the functions and variables as members.
All these extensions are incorporated in another user defined type known as
CLASS.

* By default, the member of class are private, while, by default , the members of
a structures are public.
Class & Object
• A class is a way to bind the data and its associated functions together. It allows the data and functions to be
hidden, if necessary, from external use. A class declaration is similar syntactically to a structure.
Declaration of Class:
Class class_name
{
private:
variable declaration;
function declaration;
public:
Variable declaration;
function declaration;
}
Points to remember!
❑The variables declared inside the class definition are known as data members and the
functions declared inside a class are known as member functions.
❑Wrapping of data and function and function into a single unit (i.e. class) is known as data
encapsulation.
❑By default the data members and member function of a class are private.
❑Private data members can be accessed by the functions that are wrapped inside the class.
General steps to write a C++ program using class and object:
• Header files
• Class definition
• Member function definition
• void main function
Example:
# WAP to find the SUM of two integers void Add :: calculate()
using class and object: {
#include<iostream> z=x+y;
using namespace std }
class Add void Add :: display()
{ {
int x, y, z; cout<<z;
public: }
void getdata() void main()
{ {
cout<<”Enter two numbers”; Add a;
cin>>x>>y; a.getdata();
} a.calculate();
void calculate(void); a.display();
void display(void); }
}; Output:
Enter two numbers 5 6
11
A member function can be defined:
(i) Inside the class definition
(ii) Outside side the class definition using scope resolution
operator (::)
Memory allocation for Objects
• Memory space for objects is allocated
when they are declared not when
class is specified.
• Member functions are created and
placed in the memory space only once
when they are defined.
• All objects belong to the class use the
same member function
• Space for member variables is
allocated separately for each object.
Static Data member

Use: To record the data common for all the objects of


the class.
Static Member function

setcode showcode showcount


t1 Init count =0; 1
New Count=1
Use: It could be called without existing real object. It become Code =1
useful when you want the class as a whole to have a function,
instead of each individual objects. t2 Previous Count 2 2
=1;
New count =2
Code = 2
t3 Prev count =2; 3 3
New count =3;
Code =3
Array of Object
• Collection of similar types of object is known as array of objects
Object as function argument
• Object may be used as a function argument. This can be done in two ways
1. A copy of entire object is passed to the function (pass by value)
2. Only the address of the object is transferred to the function(pass by
reference)
Pass by value:- Any change made to the object inside the function do not affect
the object used to call the function.
Pass by reference:- Here address of the object is passed, this means any change
made on object inside the function will reflect in the actual object.
Friend Function
• A friend function is a non member function or ordinary function of a class, which is declared as a friend using the keyword
“friend” inside the class.
• It has a has privilege to access private and protected data of a class.
• The keyword “friend” is placed only in the function declaration of the friend function and not in the function definition.
• Friend function can be declared in any section of the class i.e. public or private or protected.
• Scope of the function is not inside the class in which it is declared. Therefore neither name of object nor dot operator is
used to call the friend function. However it may accept the object as argument whose value it want to access.
• It cannot access directly the data members of the class like other member function. It use object through dot operator to
access data member.
Declaration of Friend Function:
Class ABC
{
…..
….
Public:
…..
…..
Friend void xyz(void);
};
Friend Class
It is possible for one class to be a friend of another class. When this is the case, the friend
class and all of its member functions have access to the private members defined within
the other class in which it is declared.
Class ABC{
….
….
Friend class min;
};
Class min{….
…..};
Member function of one class can be the friend function of another class
(Friend int classname1 :: funct();) //declaration in another class2.
Function Overloading
• It is the process by which a single function can perform different task, depending upon no of parameters and types of
parameters.
• Concept of function overloading is to design a family of function with one function name but with different argument lists.
How it works?
1. Function call first matches the prototype having the same number and types of the arguments and then call the
appropriate function for execution .
Example:
prototype
1. int add(int a, int b);
2.int add(int a, int b, int c);
3.double add(double x, double y);
4.double add(int p, double q);
5. double add(double p, int q);
Pointer in c++
• Pointer is a variable in C++ that holds the address of another variable. They have data type just like variables, for
example an integer type pointer can hold the address of an integer variable and an character type pointer can hold
the address of char variable
Syntax : data-type *pointer_name;
Declaration int *p; //can hold the address of int type variable
int var;
p = &var;
cout<<&var; // display the address of var let: var = 101, memory address = 0x62ccf
cout<<p; //display the address of var; p memory address = 0x62cff
cout<<&p; //display the address of p;
cout<<*p; //display the value of var.
Dynamic Constructor
• When allocation of memory is done dynamically using dynamic memory allocator new in a constructor, it is
known as dynamic constructor. By using this, we can dynamically initialize the objects.

Dynamic Memory Allocator:- (new and delete operators)


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.
The heap − This is unused memory of the program and can be used to allocate the memory dynamically when
program runs.
There is following generic syntax to use new operator to allocate memory dynamically for any data-type.
new data-type; (data-type can be any built in /user define data type or array)
Ex:
Int *pvalue = NULL; //pointer initialize to null
pvalue = new int; // request memory for the variable
you can free up the memory that it occupies in the free store with the ‘delete’ operator as follows :
delete pvalue; //release memory pointed by the pvalue.
#include <iostream>
using namespace std;
int main ()
{ double *pvalue = NULL; // Pointer initialized with null
pvalue = new double; // Request memory for the variable
*pvalue = 1000; // Store value at allocated address
cout << "Value of pvalue : " << *pvalue << endl;
delete pvalue; // free up the memory.
return 0;
}
o/p: 1000
Dynamic Memory Allocation for Array
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 by the pvalue.
Following the similar generic syntax of new operator, you can allocate for a multi-dimensional array as follows −
double **pvalue = NULL;
pvalue = new double[3][4]; // allocate memory for a 3x4 array
delete [ ] pvalue; // delete array pointed to 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 −
Class Add {
int a, b;
public:
void display();
};
Int main()
{ Add *obj = new Add[10];
Delete [] obj; //delete array
Pointer to member
• It is used to assign the address of member of a class and assign to the pointer.
Definition:
Class A
{ int m;
Public:
Void show();
};
Int A ::* ip = &A :: m; //definition of pointer to member.
Here, ip pointer act like class member and it must be invoked by class object.
A::* (“pointer to member of A class”)
&A ::m (“address of the m member of A class”)
Invoke:
A a; A *ap = &a; //pointer to object a
Cout<<a.*ip; cout << ap -> *ip;
Cout<<a.m; Both will display the same output. Cout<< ap -> m; display m
• Dereferencing operator ->* used to access a member when we use pointers to both the
object and the member.
• Dereferencing operator * is used when object itself is used with the member pointer

Pointer to member function


Object-name.*pointer to member function
Pointer-to-object ->* pointer- to-member-function
Constructor
• A constructor is a special member function whose task is to initialize the object of a class.
• Its name is same as the class name.
• A constructor does not have a return type.
• A constructor is called or invoked when the object of its associated class is created.
• It is called constructor because it constructs the values of data members of the class.
• A constructor cannot be virtual (shall be discussed later on).
• A constructor can be overloaded
There three types of constructor:
(i) Default Constructor
(ii) Parameterized Constructor
(iii) Copy constructor
• Default Constructor : The constructor which has no arguments is known as default constructor.
• Parameterized constructor: The constructor which takes some argument is known as parameterized
constructor.
• Copy Constructor:The constructor which takes reference to its own class as argument is known as copy
constructor.
Destructor

Tilde ~classname() { … }

A destructor is automatically called when:


1) The program finished execution.
2) When a scope (the { } parenthesis) containing local variable ends.

* Object are destroyed in reverse order.

You might also like