0% found this document useful (0 votes)
42 views35 pages

Session 2

The document provides an overview of several advanced C++ concepts including: 1) The scope resolution operator :: which allows defining class member functions outside the class declaration and accessing global variables when a local and global have the same name. 2) Dynamic memory allocation using new and delete to create objects that exist only as long as needed in memory. 3) Constructors and destructors which are special member functions for initializing and cleaning up objects. 4) The const keyword which makes objects constant and prevents modification of pointed-to objects for const pointers. 5) Static data members which create a single data item for the entire class rather than each object.

Uploaded by

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

Session 2

The document provides an overview of several advanced C++ concepts including: 1) The scope resolution operator :: which allows defining class member functions outside the class declaration and accessing global variables when a local and global have the same name. 2) Dynamic memory allocation using new and delete to create objects that exist only as long as needed in memory. 3) Constructors and destructors which are special member functions for initializing and cleaning up objects. 4) The const keyword which makes objects constant and prevents modification of pointed-to objects for const pointers. 5) Static data members which create a single data item for the entire class rather than each object.

Uploaded by

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

More on Classes

Session 2
Session Objectives
 Use the scope resolution operator
 Use dynamic memory allocation with
 New
 Delete
 Use pointers to objects
 Define and use Constructors
 Define and use Destructors
 Define the "Const" keyword
Session Objectives (Contd.)
 Define and use the "this" pointer
 Describe how objects and functions are
arranged in memory
 Static Data Members
 Static member Functions
 Describe type conversions using
 Converting by assignment
 Type casting
Scope resolution operator
 Function can be defined outside the class
specifier using a scope resolution operator ::
(double colon symbol) with the function
definition. .
 General syntax:
return_type class_name
::member_functions(arg1, arg2,. . .,argn)
 The type of member function arguments must
exactly match with the type declared in the class
specifier.
 Important for defining the member functions
outside the class declaration.
Scope resolution operator (Contd.)

 The left-hand operator of :: must be the


name of the class.
 Only the scope operator identifies the
function as a member of a particular class.
 Is also used to refer to global variable names
in cases where a global variable and a local
variable share the same name.
 The syntax used is: ::global_variable
 More freedom in naming variables.
 If two variables have different purposes, their
names should reflect the difference.
Dynamic memory allocation
 An object is created when its definition
appears in a program and it is destroyed
when its name goes out of scope or the
program terminates.
 Useful to create a new object that will exist
only as long as it is needed.
 new creates such objects and the operator
delete can be used to destroy them later.
 Objects allocated by new and delete are
said to be on the free store.
New

 The new operator is used to create a memory


space for an object of a class
 The general syntax of the new operator is:
data_type pointer_variable = new data_type;
 For example,
int *p; //pointer to integer type
float *f; //pointer to a float type
p = new int;
//allocates memory for an integer
f = new float; //allocates memory for a float
 If call to new is successful, it returns a
pointer to the space that is allocated.
New (Contd.)
 Returns zero if the space is not available or if
some error is detected.
 Same syntax for an object. For example,
Student *stu_ptr;
//pointer to an object of type Student
stu_ptr = new Student;
//points to new Student object
 The new operator is similar to the malloc()
function used in C.
Delete
 Object created by new exists until it is
explicitly destroyed by delete.
delete pointer_variable;
 Example of new and delete.
int *ptr;
ptr = new int;
*ptr = 12;
cout << *ptr;
delete ptr;
 Always a good practice to delete memory when you are
through with it.
 Be careful that you do not use pointers to memory that has
been deleted.
Allocating Arrays
 Allocate blocks consisting of arrays of varying
length using a similar technique.
int *ptr;
ptr = new int[100];
delete [] ptr;

 Any time you allocate an array of objects


using new, you must use [] in the delete
statement.
 Error to delete a variable that has been
malloc'ed and it is an error to free a
variable that was allocated with new.
Pointers to objects
 Pointers can point to objects as well as
to simple data types.
 Declaring a pointer to an object of a
particular class is the same as declaring
a pointer to a variable of any data type.
 At the time we write the program we do
not know how many objects we want to
create.
Constructors
 A constructor is a special member function for
automatic initialisation of an object.
 Has the same name as the class it belongs to.
 Can declare and define constructors within
the class, or declare them within the class
and define them outside just as any other
member functions.
Constructors (Contd.)
class username {
public:
username(); //constructor
};
username::username() { }
 No return type is used for constructors.
 Also invoked when local or temporary objects
of a class are created.
 Several constructors provide several ways of
initialising a class object.
 A default constructor is a constructor that does
not have any arguments.
Constructors (Contd.)
class date{
int month, day, year;
public:
date() //default constructor
{day=1; month=1; year=1999;}
date(int x) //only day is specified
{day=x; month=1; year=1999;}
date(int x, int y, int z) //day month year
{day=x; month=y; year=z;}
};
Constructors (Contd.)

 As long as the constructors differ sufficiently


in their argument types the compiler can
select the correct one for each use, as shown
in the examples given below.
 Each example calls a different constructor
depending on the value of the argument.
date now;
date today(4);
date all(23,3,1998);
Destructors
 A destructor is a member function that is called automatically
when an object is destroyed.
 Cannot be directly called from the class. The compiler itself
generates a call to a destructor when an object expires.
 Same name as the class but with a tilde (~) before the class
name.
class username {
public:
~username(); //destructor
};
 Destructors have no return type. They also take no

arguments.
The Const keyword

 A constant is an entity whose value does not


change during the execution of a program.
 The keyword const can be added to the
declaration of an object to make that object a
constant rather than a variable.
 A constant cannot be assigned to, so it must
be initialised.
const int num=100;
num=200; //error
num++; //error
Const with pointers

 When we use const with a pointer, there are two


objects involved. One is the pointer itself and the
other is object pointed to.
 Prefixing a declaration of a pointer with const
makes the object, but not the pointer, a constant.
Example
int num =10;
const int *iptr = &num; //pointer to the
constant
*iptr = 25; //error
num = 25; //valid, num is not constant
int xyz = 200;
iptr = &xyz; //iptr can point anywhere else
*iptr = 305; //error
Const with pointers (Contd.)
 Also possible to declare a pointer itself as a
constant rather than the object pointed to.
To do this the operator *const is used.
 Example
int a1 = 777;
//constant pointer to integer
int *const ptr = &a1;
*ptr = 66; //valid
int a2 = 45;
ptr = &a2; //error, ptr is a constant
Const with pointers (Contd.)

 The const keyword can also be used in


parameter lists to specify the valid usage of a
parameter. This feature is particularly useful
in function arguments.
void func(const char *str)
{
str = "hello"; //valid
*str = 'A'; //error
}
 Example
void func1(const int index)
{ index = 5;} //error
this pointer

 Keyword this gives the address of the object, which


was used to invoke the member function.
 Whenever a member function is called, the compiler
assigns the address of the object which invoked the
function, to the this pointer.
 Can be used like any other pointer to an object.
 Can be used to access the members of the object it
points to with the use of the arrow operator.
this->age = 5;
this->getdata();
Use of this
class Person{
private:
int age;
public:
void display();
};
void Person :: display()
{ this->age = 25; // same as age=25
cout<<this->age; // same as cout<<age
}
void main()
{ Person Jack;
Jack.display();
}
 Practical use for this is in returning values from member
functions.
Objects and functions in
memory

 Each object has its own copy of the data


members of the class.
 All the objects in a given class use the same
member functions. The member functions
are created and placed in memory only once -
when they are defined in the class specifier.
 Data is therefore placed in memory when
each object is defined, so there is a set for
each object.
Objects, data members and member
functions in memory

Object 1 Object 3

data 1 data 1
mem_function1()
data 2 data 2
mem_function2()

Object 2

data 1

data 2
Static Data Members
 Useful when all objects of the same class
must share a common item of information.
 If a data item in a class is defined as static,
then only one such item is created for the
entire class, no matter how many objects
there are.
 Only visible within the class, but its lifetime is
through the entire program.
static data_type variable;
Example

class race_cars{
private:
static int count:
int car_number;
char name[30];
public:
race_cars(){count++;} //constructor to increment count
~race_cars(){count--;} //destructor to decrement count
};
int race_cars::count;
 The static data member should be created and
initialised before the main() program begins.
The count is common
Count:
3 cars in the race
More on Static Data members
 Same as for other data members.
 If a static member is declared as a
private category of the class, the non-
member functions cannot access it.
 If it is declared as public, then any
member of the class can access.
 Static member can become a global
data for the class.
Static Member Functions

 A static member function can manipulate only


on the static data member of the class.
 Acts as global for members of its class
without affecting the rest of the program.
 It is not part of the objects of a class. It does
not have a this pointer.
 Can use a static member function to query an
object to find out which object it is.
 Useful in debugging a program, among other
situations.
Example of Static Member
Functions
class alpha{
private:
static int count; //static data member
public:
alpha(){count++;} //constructor increments
count
static void display_count() //static member
// function
{ cout<<count; }
};
Int alpha::count;
Example (Contd.)

void main()
{
alpha::display_count(); //before any object
//is created
alpha obj1, obj2, obj3;
alpha::display_count(); //after three
//objects created
}
 Even when no object has been created we
can directly call the static member using the
name of the class and the scope-resolution
operator as shown:
alpha::display_count();
Type Conversions

 Type conversion is done to convert a


variable of a declared type to some
other required type.
int count = 7;
float average = 15.5;
double totalsum = count * average;

 Converting data types can be done in


two ways:
 Converting by assignment
 Type casting
Converting by assignment

 Typical way of converting a value from one


data to another using the assignment
operator (=). Data types are considered "
higher" or "lower" in the order shown:
Highest lowest
Long double >double>float>long>int>char
 Implicit or automatic conversion: when two
operands of different types appear in the
same expression the lower-type variable is
converted to the type of the higher-type
variable.
Converting by assignment Contd.)

int xin, yin;


float aft, bft;
xin = 5; //integer assigned a value
aft = 31.0135; //float assigned a value
yin = aft; //float assigned to integer
bft = 21.5/xin;
//integer converted to float
 Converting by assignment is not
recommended since it will truncate the
fractional or real parts of a value.
 Better to explicitly convert one data type to
another using the type casting.
Type Casting

 Need to convert a value from one type to another


where the compiler will not do it automatically.
 A typical use of a cast is in forcing a division to
return a float when both operands are of the type
int.
result = float(21)/5;
Other examples:
char chs;
int x, y, z;
float aft;
x = int(chs);
aft = float(y*z);
 You can use another syntax for casts:
(int)chs;

You might also like