0% found this document useful (0 votes)
15 views17 pages

Understanding Classes and Objects in C++

- A class is an encapsulation of data and functions that operate on that data. An object is an instance of a class that occupies memory at runtime. - The this pointer contains the address of the current object and allows member functions to access the object's data members. It is passed implicitly as a hidden argument to member functions. - Static member data and functions exist for the entire class rather than each object. Static data is shared among all objects while non-static data is separate for each object.

Uploaded by

Vaibhav Chopra
Copyright
© Attribution Non-Commercial (BY-NC)
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)
15 views17 pages

Understanding Classes and Objects in C++

- A class is an encapsulation of data and functions that operate on that data. An object is an instance of a class that occupies memory at runtime. - The this pointer contains the address of the current object and allows member functions to access the object's data members. It is passed implicitly as a hidden argument to member functions. - Static member data and functions exist for the entire class rather than each object. Static data is shared among all objects while non-static data is separate for each object.

Uploaded by

Vaibhav Chopra
Copyright
© Attribution Non-Commercial (BY-NC)
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

CLASS & OBJECT

A class is encapsulation of:


•Data
•The function operating on that data

Object
An Object is an instance of a class. A class is a data
type and an object is its variable.
*The object occupies space in memory during runtime

but the class does not


#include<iostream.h>
Example
#include<conio.h>
class Counter
{
private:
int count;

public:
void initialize()
{count=0;}

void increment()
{count++;}

void decrement()
{ count--;}

int get_count()
{return count;}

}; //end of class

int main()
{
Counter c;
[Link]();

[Link]();
[Link]();
[Link]();

cout<<endl<<c.get_count();

[Link]();

cout<<endl<<c.get_count();
return 0;
}
Passing Object as Function
Argument & Returning Object
This Pointer
• Contains the address of current object
• Current object is the object with which the member function is called

Compiler does the following things automatically in a program:

It puts the address of the object as the argument with which the member
function is called

One parameter in each member function as the type of pointer of object


of that class is added. The name of the parameter is fixed , that is “this”

The “this ->” is placed before each member data in the definition of the
function, specified without any object name
Example
#include<iostream.h>
Class Where
{
private:
char charray[10]; // occupies 10 bytes
public:
void reveal()//displays the address of current object // void reveal(Where* this){…..}
{ cout<<“\nMY object’s address is “<<this;}
};
// main function
int main()
{
Where w1,w2,w3; //make these objects
[Link](); // this is the pointer of w1 // [Link](&W1);
[Link]();// this is the pointer of w2
[Link]();// this is the pointer of w3
cout<<endl;
return 0;
}
Uses of this pointer
• When an argument to a class function has the same
identifier as a class field

void Employee::setId(const int employeeIdNum)


{
this->employeeIdNum=employeeIdNum;
}

• Return the object from the member function


Static Member Data
• Each object contains its own separate data
members
• Member functions are shared amongst all
objects
• Exception: if a data member of a class is
declared as static; only one such item is
created for the entire class
Static Member Function
• You need a static function in order to access
a static field when you choose not to use an
object
• A static member function is that function
which access only static member data
• No non-static or object member data is
accessed inside the static member function
Example
#include<iostream.h>
class Counter{
static int count;
public:
static int ccount;
Counter(){count++;}
int getCount(){
return this->count; // return count;
}
static int getsCount(){
return count; // return [Link]……Error as this is not permitted for a class function
}
}; // Class Ends
int Counter::count=0;
int Counter::ccount=0;
void main(){
Counter c1,c2,c3;
cout<<[Link]()<<[Link]()<<Counter::getsCount()
<<Counter::ccount<<[Link];
}
friend Function
• Only member functions can access the
private data of a class
• Functions outside the class can also have
access to the private data of a class---Friend
Functions
• friend function acts as a bridge between two
classes
Example
#include<iostream.h>
class Jill; // Forward Reference
class Jack{
private:
int i;
public:
Jack(){i=0;}
void setVar(int var){i=var;}
int getVar(){return i;}
friend void getId(Jack,Jill);
};
Example…
class Jill{
private:
int j;
public:
Jill(){j=0;}
void setVar(int var){i=var;}
int getVar(){return j;}
friend void getId(Jack,Jill);
};
Example…
void getId(Jack ja, Jill ji){
cout<<ja.i<<endl;
cout<<ji.j;
}

void main(){
Jack ja;
Jill ji;
[Link](56);
[Link](57);
cout<<“[Link]()=“<<[Link]();
cout<<“[Link]()=“<<[Link]();
getId(ja,ji);
}
To be noted…
• Forward Reference
• friend Function declaration is necessary in
both the classes
• This declaration can be placed either in the
private section or the public section of the
class
Use of friend Function
• To access private data of a class from a
non-member function

• To increase the versatility of overloaded


operators
friend Classes
• If we make the entire class as a friend then
automatically all the member functions of
the class become friends
Example
class two;
class one
{
private:
int i;
public:
One()
{
i=10;
}

friend two;
};
class two
{
public:
fun1(one o)
{ cout<<endl<<o.i;}

fun2(one o){cout<<endl<<o.i;}
};

void main()
{
one a;
two b;

b.fun1(a);
b.fun2(a);
}

Common questions

Powered by AI

A 'friend class' enhances interaction between classes by providing all member functions of one class access to the private data of another class. This can greatly facilitate cooperation between closely related classes, enabling one class to efficiently handle and manipulate the private data of another without exposing it to the outside world. However, it should be used judiciously as it breaks the encapsulation barrier, increasing the coupling between classes and potentially introducing maintenance challenges if internal data representations change .

Friend functions are especially useful in scenarios where a function outside a class needs to access the class's private data, such as when functions need to be shared between two classes without breaking encapsulation, as demonstrated by acting as a bridge between them. Limitations of friend functions include the potential to violate the principles of object-oriented encapsulation, as they bypass the access control mechanisms that prevent external functions from modifying private data. They can also make code maintenance more challenging, as changes to private data structures may require corresponding changes in friend functions .

Encapsulation in object-oriented programming involves bundling the data with the methods that operate on that data. A class, as a blueprint, encapsulates data and functions but does not occupy memory until an object is instantiated from it, serving as a data type. On the other hand, an object is an instance of a class and directly maps to a variable that occupies space in memory at runtime. Thus, encapsulation through classes provides a structure while objects allow for dynamic data manipulation at runtime .

The 'Counter' class example distinguishing static from non-static members highlights principles of scope and storage duration by demonstrating that static members have a class-wide scope and a static storage duration, existing once per class rather than per object. As shown, the static 'count' variable accumulates a total count across all instances, whereas non-static members would manage counts individually per object. The scope of static members extends globally within the context of the class, promoting shared state across instances, whereas non-static variables are instance-specific, with temporary lifespans dependent on object lifecycles .

Static member data and functions offer several benefits in a class. Static member data is shared among all objects of a class, allowing consistent access to a common set of data across all instances. This reduces memory usage and ensures any changes to data are reflected in all instances. Static member functions can operate on static data without needing an instance of the class, enabling utility or helper functions that do not depend on object-specific data. This design supports encapsulation and efficient resource utilization while maintaining data consistency across instances .

The 'this' pointer in C++ plays a crucial role by storing the address of the current object for which a member function is called. It allows member functions to access and modify the object's data members correctly, providing a way to disambiguate between member variables and parameters with the same name. Moreover, 'this' is automatically used by the compiler to ensure each member function can properly manipulate the specific object instance it is called on by placing 'this->' before member data when needed .

The 'Counter' class example encapsulates data by managing its internal 'count' variable with private access, thus restricting direct access from outside the class. Instead, member functions such as 'initialize', 'increment', 'decrement', and 'get_count' are provided to operate on the data, demonstrating controlled interaction with the class’s data. This pattern ensures that the class maintains integrity over its data, allowing modifications only through prescribed methods, which is a key aspect of encapsulation in C++ .

Static member variables in a class are treated differently because they are not tied to specific instances of the class; rather, they are shared across all instances. This means that they are initialized separately from the class instances and have a single storage location, which helps save memory and maintain a consistent state between objects. Their initialization occurs outside the class definition, which aids readability and clarifies their scope as different from regular instance data members. Consequently, static variables provide a mechanism to store class-wide state or constants .

Forward declaration in C++ serves the purpose of informing the compiler about the existence of a class before its complete definition is provided. This is important in the context of friend functions and classes, as it allows the function or class to be referred to in declarations prior to its actual definition, facilitating relationships such as one class being declared a friend of another. For instance, declaring 'class Jill;' before using it in the 'Jack' class makes 'Jack' aware of 'Jill', allowing 'getId()' to operate collaboratively on both classes, thus enhancing modularity and reducing circular dependencies between headers .

In C++, when objects are passed as arguments or returned from functions, the operations involve the implicit use of the ‘this’ pointer, which contains the address of the current object. Unlike primitive data types, when an object is passed, a copy of the object is made unless passed by reference, which can be costly in terms of performance. Returning objects similarly involve copying unless optimizations like move semantics are applied. This behavior differs from simple data types in terms of both complexity and the potential impact on performance due to the copying overhead .

You might also like