0% found this document useful (0 votes)
1 views60 pages

Lecture 4-7

The document provides an overview of classes and objects in C++, highlighting their differences from standard C structures, encapsulation, and the use of access specifiers. It explains the structure of class declarations, member functions, and the concept of static members. Additionally, it covers object creation, memory allocation, and the various ways to pass objects as arguments in functions.

Uploaded by

aditi18702
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)
1 views60 pages

Lecture 4-7

The document provides an overview of classes and objects in C++, highlighting their differences from standard C structures, encapsulation, and the use of access specifiers. It explains the structure of class declarations, member functions, and the concept of static members. Additionally, it covers object creation, memory allocation, and the various ways to pass objects as arguments in functions.

Uploaded by

aditi18702
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/ 60

Classes and Objects

Classes

• Different from standard C structures


– Adds member functions
– Not just member data
– By default structure is public and class private
• 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 outside class, it When function is defined inside class, it
requires a prototype declaration in the class. does not require a prototype declaration in
the class.
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.
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
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 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(){}
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;
}; // declaration Nested class ends here
void EnclosingFun(Nested n)
{
cout<<n.y; // Compiler Error: y is private in
Nested }
}; // declaration Enclosing class ends here
int main(){}
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.

You might also like