0% found this document useful (0 votes)
50 views94 pages

Unit - II

Uploaded by

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

Unit - II

Uploaded by

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

Unit - II

Introduction to class
• The most important feature of C++ is the
“CLASS”
•A class is an extension of the idea of structure
used in C.
•It is a new way of creating & Implementing a
user-defined data type.
•Ex:
struct complex
{
float x;
float y;
}; struct complex C1,C2,C3;
•The complex numbers C1,C2,C3 can easily be assigned values
using the dot operator, but we cannot add two complex numbers
or subtract one from the other.
C3 = C1+C2;  illegal.
•Another important limitation is they do not permit data hiding.
•Structure members can be directly accessed by the structure
variables by any function anywhere in their scope.
•In other words, the structure members are public members.
•C++ has many characteristics to extend the C language into the
OOPS concepts.
•So all these incorporates in C++, named as class.
INTRODUCTION
• C++ class mechanism allows users to define
their own data types that can be used as
conveniently as build in types.

• Classes are often called user defined types.

• Includes defining of class types and creation of


objects of classes.
Cont…………
• The class definition introduces both :
• the class data members that define the
internal representation of class

• The class member functions that define the


set of operations that may be applied to
objects of class type.
Cont………….
• Information hiding is achieved by declaring
the data members as private whereas the
operations to be performed on class objects
by the program are public.
What is class?
• Created using keyword class.
• A class declaration defines a new user defined
data type that links code and data.
• The new data type is then used to declare
objects of that class.
• Class is a logical abstraction but an object has
physical existence.
• Objects is an instance of class.
Cont……….
• The class is the cornerstone of C++

– It makes possible encapsulation, data hiding and


inheritance
– A user defined type
– Consists of both data and methods
– Defines properties and behavior of that type
Syntax of Class declaration
• Class className
• {

• // body of a class

• }
Cont…………….
• The class definition has two parts:
• Class head : composed of keyword class
followed by the class name
• Class body: enclosed by a pair of curly
braces.
General form of class declaration
• Class className
• {
• Access_specifier_1:
• Members;
• Access_specifier_2:
• Members;
• ……
• }
• objectName;
Cont…………
• The objectName is optional.
• If present, it declares objects of the class.
Example of student class
• Class student
• {
• Int rollNo; (data members)
• Char name [25];
• Char addr [35];
• Public:
• Void getdata(); (member functions)
• Void display();
• }
• ;
Cont………
• The class data members and member
functions are declared within the body of the
class along with their access levels.
• The class body defined the class member list
and their scope.
• If two classes have members with the same
name, the program will not show any error
since the members refer to different objects.
Access specifier
• Public
• Private
• Protected
Public
• Public members may be accessed by member
functions of same class and functions
outside the scope of the class (anywhere
inside the program)
Private
• Private members may only be accessed by
member functions and friend function of the
class.
• A class that enforces information hiding
declares its data members as private.
Protected
• The protected members may be accessed only
by the member functions of its class or by
member functions of its derived class.
Cont………..
• The data hiding is achieved by declaring data
members in the private section of the class.
• Since the private members are not accessible
from outside the class, they will be accessed
by the publicly declared member functions of
the same class.
Defining a class
class box
{
Public: Int a,b,c; Data Members

void get()
{
cin>>a>>b>>c;
}
void put()
{ Member Functions
cout<<a<<b<<c;
}
};
IT 3rd Sem

Object-Oriented Programming:
Class:
class
C++ <class-name>
{
access-specifier:
variable declarations
function declarations
access-specifier:
variable declarations
function
declarations
access-specifier:
variable declarations
function
declarations
Example
• Class rectangle
• {
• Int length;
• Int width;
• Public:
• Void setvalues (int,int);
• Int area();
• };
Cont………..
• It declares a class rectangle. The class contains
four members:
• Two data members length and width of type
integer in the private section (because private
section is default permission)
• Two member functions:
• Setvalues (int, int) and area() in the public
section.
IT 3rd Sem

C+
Object-Oriented Programming:
Object:
class
+ <class-name>
{
access-specifier:
variable declarations
function declarations
access-specifier:
variable declarations
function
declarations
} ob1;
//object
void creation
main()
{
<class-name> ob2; //object
creation
Objects

A class provides the blueprints for objects, so basically an


object is created from a class. Object can be called as an
instance of 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;
Box Box2;
Cont………..
• The definition of class does not cause any
storage to be allocated. Storage is only
allocated when object of class type is defined.

• The process of creating objects of the class is


called class instantiation.
Syntax of defining objects of a class
• Class className objectName
• Class : keyword
• ClassName : user defined class name
• User defined object name
Object Operations

All operations that can be applied to basic data types can be


applied to the objects.
E.g.:
• Arithematic
• Relational
• Logical
Example
• Class rectangle
• {
• Int length;
• Int width;
• Public:
• // member functions
• };
• The definition
• Rectangle rect;
Cont………..
Will allocate the memory space sufficient to
contain the two data members of the rectangle
class.
The name rect refers to that memory location.
Each class object has its own copy of the class
data members.
• An object of a class type also has a lifetime.
Data members
• Declared in the same way as the variables are
declared.
• Generally, all data members of a class are
made private to that class.
• If data members are declared in the public
section of the class, they will be accessed
using member access operator, dot (.).
Syntax of accessing data members of
class
• objectName . Data member

• ObjectName : user defined object name


• . : member access operator
• Data member: data member of a class.
Member functions
• Functions that are declared within a class are
called member functions.
• Works on data members of class.
• Member functions can access any element of
the class of which they belong to.
• The member functions of a class are declared
inside the class body.
Syntax of accessing member functions
of a class
• objectName . functionName (Actual
Arguments)

• objectName: user defined object


name
• . : member access operator
• functionName: name of the
member function
• Actual arguments: arguments list to the
Cont…………
• Member functions are declared within the
scope of their class. It means member
function is not visible outside the scope of its
class.
Member function can be defined in
two ways
• Inside the class
• Outside the class
Functions defined inside the class
• Member function of a class can be defined
inside the class declaration.
• Its syntax is similar to a normal function
definition except that it is enclosed within the
body of a class.
Example
• The member function in the rectangle class can be defined as follows:
• Class rectangle
• {
• Int length;
• Int width;
• Public:
• Void setvalues(int x, int y)
• {
• Length = x;
• Width = y;
• }
• Int area ()
• {
• return(length * width);
• }
• };
Cont…….
• In this the class contains two member
functions in the public section:
Setvalues(int, int)
Area()

• They are defined


inside the class
itself.
Functions defined outside the class
• In this method, the prototype of the member
function is declared within the body of the
class and then defined outside the body of the
class.
• Functions defined outside the class have the
same syntax as the normal function, there
should be a mechanism of binding to the class
to which they belong.
Cont……………
• This requires a special declaration.
• The name of the member function must be
qualified by the name of its class by using the
scope resolution operator. ( : : )
General format of member function
definition
• Class className
• {
• ……
• returnType memberFunction (arguments);
• User defined class name
• }
• ;
Member function definition outside
the class
• returnType className :: memberFunction
(arguments)
• {
• // body of the function
• }
Implementing Class Functions
• When you construct a class, you create two parts:
– Declaration section: contains the class name,
variables (attributes), and function prototypes
– Implementation section: contains the
functions
• Use both the class name and the scope resolution
operator (::) when you implement a class function

Object-Oriented Programming
42
Using C++, Third Edition
Implementing Class Functions
(continued)

Object-Oriented Programming
43
Using C++, Third Edition
Memory allocation for Objects
•Memory space for objects is allocated when they
are declared and not when the class is specified. This
statement is partly true.

•Actually the member functions are created & placed


in the memory space only once when they are
defined a part of a class specification.
Characteristics of static data members:
1. It is initialized to zero when the first object of
its class is created. No other initialization is
permitted.
2. 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.
3. It is visible only within the class, but its
lifetime is the entire program.
Using Static Class Members
• When a class field is static, only one memory
location is allocated
– All members of the class share a single storage
location for a static data member of that same class
• When you create a non-static variable within a
function, a new variable is created every time you
call that function
• When you create a static variable, the variable
maintains its memory address and previous value
for the life of the program
Object-Oriented Programming
44
Using C++, Third Edition
Static variable
• Static variables are sometimes called class
variables, class fields, or class-wide fields
because they don’t belong to a specific object;
they belong to the class.
• Initialized and allocated storage only once at
the beginning of the program execution.
• No matters how many times they are called
and used in the program.
• Retains its value until the end of the
program.
Static Members
• Static variables:
- Shared by all objects of the class
- Like a “global variable” among objects of the
class
• Static member functions:
- Can be used to access static member
variables
- Can be called before any objects
are created

Chapter 11 Starting Out with © 2006 Pearson Education.


C++: Early Objects 5/e All Rights Reserved
slide 46
Static member function characteristics
1. A static function can have access to only
other static members
2. A static member function can be called using
the class name

Class name :: function_name;


Constant Member Functions
• Declared with keyword const
• When const follows the parameter list,
int getX() const; (in the class definition)
int X::getX() const (defined outside the class)
the function is prevented from modifying
the object
– can’t change the object attributes
• When const appears in the parameter
list,
int setNum (const int num)
the function is prevented from modifying
the
parameter. The parameter is read-only.
Chapter 11 Starting Out with © 2006 Pearson Education.
C++: Early Objects 5/e All Rights Reserved
slide 47
Constructor
1. C++ provides a special member function called the
constructor which enables an object to initialize itself when it
is created. This is known as automatic initialization of objects.
2. A constructor is a special member function whose task it to
initialize the data members of an object of its class.
3. It is special because it has same name as its class name
4. It invokes automatically whenever a new object of its
associated class is created.
5. It is called constructor because it constructs the initial values
of data members and build your programmatic object.
6. Constructor never have any return value including void.
Constructors
7. Constructors & destructors should be declared in public area
8. Constructors may or may not have arguments.
9. It also having default arguments & it is executed only once
when the object is created.
10. It used to initialize the number variables.
11. It should be declared with the public.
12. There is no need to write any statement to invoke the
constructor function.
13. If a ‘normal’ member function is defined for initialization, we
need to invoke that function for each and every objects
separately.
14. If no constructor is defined in the class in such a situation the
compiler implicitly provides a constructor, which is called
default constructor
Characteristics of Constructor
1. They should be declared in the public sector.
2. They are invoked automatically when the objects are created.
3. They do not have return types, not even void.
4. They cannot be inherited, though a derived class can call the
base class constructor.
5. Like other C++ functions, they can have default arguments.
6. Constructors cannot be virtual.
7. We cannot refer to their addresses.
8. An object with a constructor cannot be used as a member of
a union.
9. They make implicit calls to the operators new & delete when
memory allocation is required.
Example
class integer
{
int m,n;
public:
integer(int x, int y);
----
};
integer : : integer(int x, int y)
{
m=x, n=y;
}
Types of Constructors
1. Default Constructor / Non-arg Constructor

2. Parameterized Constructor

3. Copy Constructor

4. Dynamic Constructor
Default constructor
1. A constructor without any argument is known as default
constructor.
2. If no constructor defined in the class, then compiler
implicitly provides an empty body constructor which is
called as default constructor.
Ex: class circle
{
float radius;
Public:
circle( )
{
radius = 0;
}
};
Parameterized Constructor
1. Sometimes it is necessary to initialize the various
data elements with different values when they
are created.
2. This is achieved by passing arguments to the
constructor function when the objects are
created.
3. The constructors that can take arguments are
called Parameterized Constructors
Two ways of calling a constructor
1. Implicit call(shorthand method)
circle ob(7.6);
2. Explicit call
circle ob;
ob = circle(7.6);
Copy Constructor
1. A copy constructor is used to declare and initialize an
object from another object.
integer(integer & i);
integer I2(I1) or integer i2=i1;
2. The process of initializing through a copy constructor is
known as copy initialization.
3. The statement i2=i1 will not invoke the copy constructor
4. If i1 and i2 are objects, this statement is legal and assigns
the values of i1 to i2, member-by-member.
5. A reference variable has been used as an argument to the
copy constructor.
6. We cannot pass the argument by value to a copy
constructor.
Dynamic constructors
1. The constructors can also be used to allocate
memory while creating objects.
2. This will enable the system to allocate the right
amount of memory for each object when the
objects are not of the same size.
3. Allocation of memory to objects at the time of
their construction is known as dynamic
construction of objects.
4. The memory is allocated with the help of the
new operator.
circle ob(100)
Dynamic initialization of objects
1. Providing initial values to objects at run time.
2. Advantages –
 We can provide various initialization formats,
using overloaded constructors.
 This provides the flexibility of using different
format of data at run time depending upon the
situation.
Constructors with default arguments
1. It is possible to define constructors with default
arguments.
complex(float real, float imag=0)
2. The default value of the argument imag is zero. Then the
statement
complex c(5.0); assigns the value 5.0 to the real variable
& 0.0 to imag(by default)
ex : complex c(2.0,3.0)
A : : A( )  default constructor
A : : A (int = 0)  Default argument constructor
3. The default argument constructor can be called with
either one argument or no arguments.
4. When called with no arguments, it becomes a default
constructor
Multiple constructors in a class
1. C++ permits to use more than one constructor in a class.
2. Add( );  no arguments
3. Add(int, int)  two arguments
class add
{
int m,n;
Public:
add ( ){ m=0; n=0;}  first constructor
add(int a, int b)  second constructor
{ m=a; n=b; }
add(add &i)  third constructor
{ m=i.m; n=i.n;}
};
Destructors
1. As the name implies, it is used to destroy the objects that
have been created by a constructor.
2. Like a constructor, the destructor is a member function
whose name is the same as class name but is proceded by a
tilde.(~)
~integer()
{
}
3. It never takes any argument nor does it return any value.
4. It will be invoked implicitly by the compiler upon exit from the
program to clean up storage that is no longer accessible.
5. It is good practice to declare destructors in a program since it
releases memory space for future use.
Objects as Function Arguments
An object may be used as an function argument.
This can be done by two ways,
1. A copy of the entire object is passed to the function
 This is called pass by value. Since a copy of the object is
passed to the function, any changes made to the object
inside the function do not affect the object used to call
the function.
2. Only the address of the object is transferred to the
function
 This is called pass-by-reference. When an address of the
object is passed, the called function works directly on
the actual object used in the call. This means that any
changes made to the object inside the function will
reflect in the actual object.
Returning objects
A function can not only receive objects as
arguments but also can return them.
This is called returning objects
The this Pointer and Constant
Member Functions

• this pointer:
- Implicit parameter passed to a
member function (by the compiler)
- points to the object calling the function
• const member function:
- does not modify its calling object

Chapter 11 Starting Out with © 2006 Pearson Education.


C++: Early Objects 5/e All Rights Reserved
slide 48
This pointer
• When a member function is called, an implicit
argument is automatically passed that is a
pointer to the invoking object (that is,
object on which the function is called). This
type of pointer is called this.
Using the this

Pointer
Can be used to access members that may
be hidden by parameters with same name:
class SomeClass
{
private:
int num;
public:
void
setNum(i
nt num)
{ this-
>num =
C++: Early Objects 5/enum; }
Chapter 11 Starting Out with © 2006 Pearson Education.
All Rights Reserved
slide 50
Constant keyword
• In c++, constant keyword is used to make
program elements constant. Constant keyword
can be used with:
• Variable
• Pointer
• Function arguments and return types
• Class data member
• Class member function
• objects
IT 3rd Sem

C+
Object-Oriented Programming:
+
Types of Member Functions:

 Inline Functions

 Nested Functions

 Friend Functions

 Static Functions

 Virtual Functions
FRIEND FUNCTION
• The protected and private members cannot be
accessed from outside the same class at
which they are declared.
• Its possible to grant a non member function
access to the private members of a class,
by using a keyword friend.
Cont………
• A friend function has access to all private and
protected members of the class for which it is
friend.
Syntax of friend function
• Class rectangle
• {
• ……
• …..
• Public:
• ……
• ……
• Friend rectangle duplicate (rectangle)
• }
Characteristics of friend function
1. It is not member function of the class.
2. It is like normal external functions.
3. It is not in the scope of the class to which it
has been declared.
4. It can be declared either public or private
section of the class.
5. Usually it passes objects as arguments.
Friends of Classes

• Friend function: a function that is not a


member of a class, but has access to private
members of the class
• A friend function can be 1) a stand-alone
function or 2) a member function of another
class
• It is declared a friend of a class with the
friend keyword in the function prototype
Chapter 11 Starting Out with © 2006 Pearson Education.
C++: Early Objects 5/e All Rights Reserved
slide 57
Friend Class Declaration
3) An entire class can be declared a friend of a
class:
class aClass
{private:
int x;
friend
class
frClass
;
};
class
frClass
{public:
void fSet(aClass &c,int a){c.x = a;}
int fGet(aClass c){return c.x;}
};C++: Early Objects 5/e
Chapter 11 Starting Out with © 2006 Pearson Education.
All Rights Reserved
slide 58
Friend Class Declaration
• If frClass is a friend of aClass, then
all member functions of frClass have
unrestricted access to all members of
aClass, including the private members.

• In general, restrict the property of Friendship


to only those functions that must have access
to the private members of a class.

Chapter 11 Starting Out with © 2006 Pearson Education.


C++: Early Objects 5/e All Rights Reserved
slide 59
Nested class
• A class can be defined within other class, such
a class is called nested class.
• A member of its enclosing class.
• Its definition can occur within a public,
protected or private section of its enclosing
class.
Local classes
• A class that can be defined inside a function
body. Such a class is called local class.
• It is only visible in the local scope in which it is
defined.
Abstract class
• An abstract class is a class that is designed to
be specifically used as a base class.
• An abstract class contains at least one pure
virtual function.
• You declare a pure virtual function by using
a pure specifier (= 0) in the declaration of a
virtual member function in the class
declaration.
Cont………..
• You cannot create an object of an abstract
class type; however, you can use pointers and
references to abstract class types.
• A class that contains at least one pure virtual
function is considered an abstract class.
• Used to provide an interface to its sub
classes.
Pure virtual functions
• Functions with no definition.
• They start with keyword virtual and ends with
=0
• Syntax is:
• Virtual void f() = 0;
container classes
• A Container class is defined as a class that
gives you the power to store any type of data.
• There are two type of container classes in C++,
namely
• “Simple Container Classes” and
• “Associative Container Classes”.
• An Associative Container class associates a key
to each object to minimize the average access
time.
Cont………
• Simple Container Classes

* vector<>
* lists<>
* stack<>
* queue<>
* deque<>
Cont…………
• Associative Container Classes

* map<>
* set<>
* multimap<>
* multiset<>
Storage classes
• Used to specify the lifetime and scope of the
variables.
• How storage is allocated for variables and how
variable is treated by complier depending
upon these storage classes.
5 types
1. Local variable
2. Global variable
3. Register variable
4. Extern variable
5. Static variable
Namespace
• Container for identifiers.
• Puts the names of its member in a distinct
space so that they don’t conflict with the
names in other namespaces.
Synta

x
Its creation is similar to class creation
• Namespace Myspace
• {
• Declarations
• }
• Int main() {}
Will create namespace named Myspace, in
which we put member declarations.
Class member function
• A member function of a class is a function that
has its definition or its prototype within the
class definition like any other variable.
Class access modifier
• A class member can be defined as public,
private or protected. By default
members would be assumed as private.

You might also like