You are on page 1of 73

Classes and Objects

Classes

• Different from standard C structures


– Adds member functions
– Not just member data
• Integral to object-oriented programming
– Focus on objects
• Object: Contains data and operations
• In C++, variables of class type are objects
Specifying a Class

• A class is a way to bind the data and its associated


functions together.
• It is created using the keyword class.
• A class is a way to bind the data and its associated
functions together.
• A class specification has 2 parts:
– Class declaration
– Class function definitions
Specifying a Class

• Class declaration:
 describes new type that links code and data.
 describes scope of its members.
• Class function definitions: describes how the class functions
are implemented.
• Class is the logical abstraction.
General form of Class declaration
Difference between Structure and
Class
• By default, members of class are private, while, by
default, members of structure are public.

• Encapsulation

• The keywords public and private are known as


visibility labels.
A Simple Class Example
class item
{
int number;
float cost;
public :
void getdata(int a, float b);
void putdata (void);
};
Class Representation

Creating Objects:
item x;

Accessing Class Members:


Object_name.function-name (actual-arguments);
x.getdata(100, 75.5); x.putdata( );
Creating Objects
• Objects can also be created as follows:

• An object has physical existence.


• An object is an instance of a class.
Complete Example of a Class - 1
#include <iostream>
using namespace std;
class myclass
{
public:
int i, j, k; // accessible to entire program
};
int main()
{
myclass a, b;
a.i = 100; // access to i, j, and k is OK
a.j = 4;
a.k = a.i * a.j;
b.k = 12; // remember, a.k and b.k are different
cout << a.k << " " << b.k;
return 0;
}
Complete Example of a Class - 2
#include <iostream>
using namespace std;
class myclass
{
int a, b;
public:
void init(int i, int j) { a=i; b=j; }
void show() { cout << a << " " << b << "\n"; }
};
int main()
{
myclass x;
x.init(10, 20);
x.show();
return 0;
}
Memory Allocation for Objects

• Memory space for objects is allocated when they are


declared and not when the class is specified : partially
true.
• Since all the objects belonging to that class use the same
member functions, no separate space is allocated for
member functions when the objects are created.
• Only space for member variables is allocated separately
for each object. Because, member variables will hold
different data values for different objects.
Example
Member Functions
Defining Member Functions
• Outside the class definition • Inside the class definition
When function is defined inside class, it does
When function is defined outside class, it not require a prototype declaration in the
requires a prototype declaration in the class. class.
Nesting of Member Functions
Nesting of Member Functions

• An object of a class using dot operator generally calls a


member function of the class.

• However, a member function may also be called by using its


name inside another member function of the same class.

• This is known as “Nesting of Member Functions”


Nesting of Member Functions
Access Specifiers
Data Hiding Revisited
Access Specifier: Public

• Public members are accessible outside the class.

• Public members are accessible to both member Functions and


non-member Functions.

• Objects can access the members directly using dot operator.


E.g.
– object name.public data member
– object name.public member function 
Access Specifier: Public
Access Specifier: Private

• Private Members can only be accessed by the member


functions of that class.

• They cannot be accessed by any non member functions (data


is hidden from outside world).

• Object of a class cannot access private members using dot


operators.

• All data at the beginning of a class is by default private, until


any specifier is mentioned.
Access Specifier: Private
Private Member Functions
Private Member Functions
Protected Member Functions

• It is needed only when inheritance is involved.


• Once the access specifier has been used, it
remains in effect until either another access
specifier is encountered or the end of the class
declaration is reached.
• We may change access specifications as often
as you like within a class declaration.
#include<iostream>
#include<cstring>
using namespace std;
class employee
{
char name[80]; //private by default
public:
void putname(char *n); //these are public
void getname(char *n);
private:
double wage; //private, again
public:
void putwage(double w); //back to public
double getwage();
};
Restrictions on class members

• A non-static member variable cannot have an


initializer.
• No member can be an object of the class that
is being declared.
• No member can be declared as auto, extern or
register.
Structures and Classes are related

• Structures are part of C subset and were


inherited from C language.
• Class is syntactically similar to struct.
• In C++ role of structure was expanded,
making an alternative way to specify a class.
• Difference between struct and class: By
default all members are public in struct and
private in class.
• In C++, structure defines a class type.
#include <iostream>
#include <cstring>
using namespace std;
struct mystr
{
void buildstr(char *s); // public
void showstr();
private: // now go private
char str[255];
};

void mystr::buildstr(char *s)


{
if(!*s) *str = '\0'; // initialize string
else strcat(str, s);
}
void mystr::showstr()
{
cout << str << "\n";
}
int main()
{
mystr s;
s.buildstr(""); // init
s.buildstr("Hello ");
s.buildstr("there!");
s.showstr();
return 0;
}
The class mystr could be rewritten by using class
as:
class mystr
{
char str[255];
public:
void buildstr(char *s); // public
void showstr();
};
• In C, structure provides means of grouping
data. Therefore, class allow them to include
member functions.
• As structures and classes are related, so,
porting of existing C programs to C++ is easier.
It is better to use class when we want to use class
and struct when we want to C-like structure
i.e. that does not contain member functions,
constructors or destructors (known as
POD(Plain Old Data)).
Object
Object
#include <iostream>
using namespace std;
class myclass
{
int a, b;
public:
void init(int i, int j) { a=i; b=j; }
void show() { cout << a << " " << b << "\n"; }
};
int main()
{
myclass x; //Single object
x.init(10, 20);
x.show();
return 0;
}
Array of Objects
In C++, it is possible to have arrays of objects.
#include <iostream>
using namespace std;
class cl
{
int i;
public:
void set_i(int j) { i=j; }
int get_i() { return i; }
};
int main()
{
cl ob[3]; //Array of Objects
int i;
for(i=0; i<3; i++)
ob[i].set_i(i+1);
for(i=0; i<3; i++)
cout << ob[i].get_i() << "\n";
return 0;
}
Passing Objects as Arguments
• In C++, we can pass class’s object as argument
to a function in the same way as any other type
of variable is passed.
• It uses standard call-by-value mechanism.
• No special keyword or header file is required .
• It creates the local copy of the object in the
function scope.
• Things you modify in the object passed to the
function, won’t be reflected in the object
passed to it.
• While calling, syntax is :
function_name (object_name);
• Others ways to pass the object to function as argument
are:
 Pass by Reference
 Things modified here will be reflected back.
 No copy of object is created.
 Pass by const Reference
 Cannot modify/reassign the object directly.
 Useful if we want the function to have only a read only
copy of the object.
 No copy of object is created.
 Pass by const Pointer
You cannot modify/reassign the pointer here.
Useful only when we want function to have only
the address of this object in the pointer.
No copy of the object is created.
using namespace std;
class Example {
public:
    int a;
      // This function will take an object as an argument
    void add(Example E)
{
        a = a + E.a;
    }
};
 // Driver Code
int main()
{
    // Create objects
    Example E1, E2;
      // Values are initialized for both objects
    E1.a = 50;
    E2.a = 100;
cout << "Initial Values \n";
    cout << "Value of object 1: " << E1.a   << "\n& object 2: " << E2.a << "\n\n";
      // Passing object as an argument to function add()
    E2.add(E1);
      // Changed values after passing object as argument
    cout << "New values \n";
    cout << "Value of object 1: " << E1.a    << "\n& object 2: " << E2.a  << "\n\n";
     return 0;
}
Output will be:
Initial Values
Value of object 1: 50
& object 2: 100
New values
Value of object 1: 50
& object 2: 150
Returning Object from Function
As, function can return value. The value can be of any
data type such as int, float, char, struct, etc. Now,
function can also return an object.
Syntax:
object = return object_name;
#include<iostream>
using namespace std;
class sample
{
int x;
public:
void getdata(int a)
{
x=a;
}
void display()
{
cout<<x;
}
sample sum(sample b)
{
sample c;
c.x=x+b.x;
return(c);
}
};
int main()
{
sample obj1, obj2, obj3;
obj1.getdata(10);
obj2.getdata(20);
obj3=obj1.sum(obj2);
obj3.display();
return 0;
}
Static Class Members
Static Data Member

• Static data members are data objects that are common


to all objects of a class
• They exist only once in all objects of this class i.e. only
one copy of that member is created for the entire class.
• They are used when the information is to be shared.
• It can be public or private data.
• They should be created and initialized before the main
function block begins.
• By default, static data member is initialized to zero
when the first object of its class is created.
• When you declare a static data member within a
class, you are not defining it.
• Instead, a global definition is provided for it
elsewhere, outside the class.
• This is done by redeclaring the static variable using
the scope resolution operator to identify the class to
which it belongs. This causes the storage to be
allocated to the variable.
Syntax:
class sample
{
int a, b;
static int total; //static data declaration
public:
……..
};
int sample:: total=0; //static data definition
main()
{
…..
……
}
#include<iostream>
using namespace std;
class sample
{
static int count; //declaration of static data member
public:
void display();
};
int sample::count; //static data definition and intilize to 0 by default
void sample:: display()
{
++count;
cout<<“value of count=“<<count<<endl;
}
int main()
{
sample c1,c2,c3;
c1.dispaly();
c2.display();
c3.display();
return 0;
}
Uses of Static data member

• It provide access control to some shared resources


used by all objects of a class. So, only one object can
be allowed to write to the file at a time.
• To keep track of the number of objects of a particular
class type that are in existence.
Static Member Function
• We can declare a member function as Static by
prefixing “static” before the function name.
• Has the same properties as static data member.
• Static member functions are common to the class and
independent of any object.
• Static function can access and manipulate only on
static data member of the class.
Static Member Function
• As static member function is independent of any
object. So, it is called using class name instead of its
object.
• Syntax:
class_name:: static_function_name();
#include<iostream>
using namespace std;
class account
{
static int count;
public:
static void display()//static member function
{
count++;
cout<<“The value of count=“<<count<<endl;
}
};
int account::count=50; //static data definition

int main()
{
account obj1,obj2;
account::display(); //accessing static function
account obj3;
account::display();
return 0;
}

Output:
The value of count= 51
The value of count= 52
Restrictions on Static Member
Function
• They may directly refer to the other static members of
the class.
• A static member function does not have a this pointer.
• There cannot be a static and non-static version of the
same function.
• A static member function may not be virtual.
• They cannot be declared as const.
Use:
To “Preinitialize” private static data before any object is
actually created.
Inline Functions

• In C++, you can create short functions that are not


actually called; rather, their code is expanded in line
at the point of each invocation.
• This process is similar to using function-like macro.
• To cause a function to be expanded in line rather than
called, precede its definition with the inline
keyword.
Inline Functions
• We can define a member function outside the class definition
and still make it inline by using the qualifier inline in the
header line of the function definition.
#include <iostream>
using namespace std;
inline int max(int a, int b)
{
return a>b ? a : b;
}
int main()
{
cout << max(10, 20);
cout << " " << max(99, 88);
return 0;
}
As far as compiler is concerned, the preceding program is equivalent to:

#include <iostream>
using namespace std;

int main()
{

cout << (10>20 ? 10 : 20);


cout << " " << (99>88 ? 99 : 88);

return 0;
}
Advantage of Inline Functions:
• It allows to create efficient code.
• Each time a function is called:
 a significant amount of overhead is generated by the
calling and return mechanism.
 Arguments are pushed onto stack
 Various registers are saved when a function is called
and then restored when the function returns.
So, these steps take lot of time. When functions are
expanded inline, none of these operations occur.
• Use of inline functions produce faster run
times, although it results in larger code size
because of duplicated code. So, it is best to
inline only very small functions.
• It is better to inline only those functions which
have significant impact on the performance of
program.
• Inline is a request to a compiler not a
command. Compiler can ignore it also. Some
compilers may not inline all type of functions.
• If function is not inlined, it will be called as
normal function.
• Inline functions may be class member
functions.
#include <iostream>
using namespace std;
class myclass {
int a, b;
public:
void init(int i, int j);
void show();
};
// Create an inline function.
inline void myclass::init(int i, int j)
{
a = i;
b = j;
}
// Create another inline function.
inline void myclass::show()
{
cout << a << " " << b << "\n";
}
int main()
{
myclass x;
x.init(10, 20);
x.show();
return 0;
}
• When function is defined inside a class declaration, it is automatically
made into an inline function (if possible).
• It is not necessary to precede its declaration with the inline keyword.
#include <iostream>
using namespace std;

class myclass {
int a, b;
public:
// automatic inline
void init(int i, int j)
{
a = i;
b = j;
}

void show()
{
cout << a << " " << b << "\n";
}
};
Constant Member Functions

• Can declare member function as a constant


member function, in order to ensure that the
member function does not alter the values
passed to it.
This is done to ensure that the data is not
corrupted.
#include<iostream>
class date
{
int day, month, year;
public:
void getdata(int a, int b, int c)
{
day=a;
month=b;
year=c;
}
void display() const //constant function defined
{
cout<<“Date is”<<day<<“-”<<month<<“-”<<year;
}
};
int main()
{
date d;
d.getdata(15,11,19);
d.display();
return 0;
}
Nested Classes

• A class is declared within another class.

• The outer class is called enclosing class and inner class


is called the nested class.

• A nested class is a member and as such has the same


access rights as any other member.

• The members of an enclosing class have no special


access to members of a nested class; the usual access
rules shall be obeyed.
Nested Classes

• A nested class is valid only within the scope of


the enclosing class.
• But, nested classes are seldom used due to C+
+’s flexibility and inheritance mechanism.
So, the need for nested classes is virtually non-
existent.
Nested Classes Example
#include<iostream>
using namespace std;
class Enclosing /* start of Enclosing class declaration */
{
int x;
class Nested
{ /* start of Nested class declaration */
int y;
void NestedFun(Enclosing e)
{
cout<<e.x; // works fine: nested class can access
// private members of Enclosing class
}
}; // declaration Nested class ends here
}; // declaration Enclosing class ends here
int main(){}
Local Classes
• A class may be defined within a function i.e. class
declared within a function is known only to that function
and unknown outside of it.
Restrictions on local classes:
• All member functions must be defined within the class
declaration.
• The local class may not use or access local variables of
the function in which it is declared.
• No static variable may be declared inside the local class.
Due to these restrictions, local classes are not common in
C++ programming.
#include <iostream>
using namespace std;
void f();
int main()
{
f();
// myclass not known here
return 0;
}
void f()
{
class myclass {
int i;
public:
void put_i(int n) { i=n; }
int get_i() { return i; }
} ob;

ob.put_i(10);
cout << ob.get_i();
}
Thank You

You might also like