0% found this document useful (0 votes)
16 views

Chapter 4 - Classes and Objects

Uploaded by

basur00basur
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Chapter 4 - Classes and Objects

Uploaded by

basur00basur
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

College of Business, Science &Technology (CBST), Mymensingh

Department of Computer Science and Engineering

Object Oriented Programming (OOP)

Chapter - Classes & Objects

Prepared by
Md. Masum Billah
Lecturer, Dept. of CSE, CBST
Mobile: 01793200796
1. What is Class?

Class is a user defined data type, which holds its own data members and member functions, which can be
accessed and used by creating an instance of that class. A class is like a blueprint for an object. A class
definition starts with the keyword class followed by the class name and the class body, enclosed by a pair of
curly braces. General format of declaration of class is following –

class className
{
Access Specifier: // can be private, public, protected
// data member
// member functions

};

2. How does class Accomplish data hiding?

Data hiding is a technique of hiding internal object details, i.e., data members. It is an object-oriented
programming technique. Data hiding ensures, or we can say guarantees to restrict the data access to class
members. It maintains data integrity.

Data hiding means hiding the internal data within the class to prevent its direct access from outside the class.

Data hiding is achieved through the use of access modifiers such as private, protected, and public. While,
Encapsulation is achieved by defining the data members of a class as private and providing public methods,
known as getters and setters, to access and modify the data.

#include <iostream>
using namespace std;

class MyClass {
private:
int Data;

public:
void setData(int data) {
Data = data;
}

int getData() {
return Data;
}
};

int main() {

MyClass obj;
// obj.Data = 10; // This would be an error since privateData is private
obj.setData(10);
cout << "Data: " << obj.getData() << endl;

return 0;
}

Output:

Data: 10
3. What is object? Explain how we can create objects of a class?

Object is an instance of a class. All data members and member functions of the class can be accessed with the
help of objects. When a class is defined, no memory is allocated, but memory is allocated when it is
instantiated (i.e. an object is created).

Declaring Objects: When a class is defined, only the specification for the object is defined; no memory or
storage is allocated. To use the data and access functions defined in the class, we need to create objects.
Syntax:

ClassName ObjectName;

Example-
className ob1,ob2,ob3;

would create the objects ob1, ob2, and ob3 of type Item.

4. How can we access the class members?

Accessing a data member depends solely on the access control of that data member. If it’s public, then the
data member can be easily accessed using the direct member access (.) operator with the object of that class.

Accessing Public Data Members


class Student
{
public:
int rollno;
string name;
};

int main()
{
Student A;
A.rollno=1;
A.name="Masum";
cout <<"Name and Roll no of A is: "<< A.name << "-" << A.rollno;
}

If, the data member is defined as private or protected, then we cannot access the data variables directly. Then
we will have to create special public member functions to access, use or initialize the private and protected
data members. These member functions are also called Accessors and Mutator methods
or getter and setter functions.

Accessing private Data Members


class Student
{
private: // private data member
int rollno=7;

public:
// public function to get value of rollno - getter
int getRollno()
{
return rollno;
}
};

int main()
{
Student A;
cout<< A.getRollno();
}

Output: 1

5. How can we access private member function of a class?

In object-oriented programming, private member functions can be accessed by other member functions within
the same class. This encapsulation mechanism ensures that only the class's own methods can interact with its
private data and behavior .

Example:

#include <iostream>

using namespace std;

class MyClass {
private:
void privateFunction() {
cout << "Private function called" << endl;
}

public:
void publicFunction() {
privateFunction(); // Accessing private function
}
};

int main() {
MyClass obj;
obj.publicFunction(); // This will call the private function indirectly
return 0;
}

6. Write down the characteristics of member functions.

The member functions have some special characteristics that are often used in the program development.
Those characteristics are following-

1. Several different classes can use the same function name. The “membership level” will resolve their
scope
2. Member functions can access the private data of a class non member function can't do so
3. A member function can call another member function directly without using dot(.) operator.
7. What are the various function that can have access to private and protected member of a
class?

The following types of functions can access private and protected members of a class:

1. Member Functions: Functions defined within the class itself have access to all private and protected
members.

2. Friend Functions: Functions declared with the friend keyword within the class. Friend functions are not
members of the class but can access private and protected members as if they were.

3. Friend Classes:When an entire class is declared as a friend using the friend keyword, all member
functions of that friend class have access to the private and protected members of the class declaring the
friendship.

8. How memory allocated for an object? Explain.

Memory allocation for an object: Before using a member of a class, it is necessary to allocate the
required memory space to that member. The way the memory space for data members and member functions
is allocated is different regardless of the fact that both data members and member functions belong to the
same class. The memory space is allocated to the data members of a class only when an object of the class is
declared, and not when the data members are declared inside the class. Since a single data member can have
different values for different objects at the same time, every object declared for the class has an individual
copy of all the data members.

On the other hand, the memory space for the member functions is allocated only once when the class is
defined. In other words, there is only a single copy of each member function, which is shared among all the
objects. For instance, the three objects, namely, book1, book2 and book3 of the class book have individual
copies of the data members title and price. However, there is only one copy of the member functions getdata ()
and putdata () that is shared by all the three objects.

9. Encapsulation reduces complexity- justify your position.

Encapsulation reduces complexity in software development by bundling data and methods into self-contained
units called classes, and restricting direct access to some components. This promotes modularity, making it
easier to manage, understand, and maintain each class independently. Encapsulation enhances maintainability
by allowing internal changes without affecting other parts of the system, aiding in debugging and testing.

It also increases reusability, as encapsulated classes with consistent interfaces can be reused across different
projects. Additionally, encapsulation provides data protection and controlled access, ensuring data integrity
and reducing the cognitive load on developers by simplifying interfaces and promoting abstraction.
10. Relation between class and object.

A class is like a blueprint or template that defines the structure and behavior of something. An object is an
instance of that class, created based on the blueprint.

In programming:
- Class: Defines attributes (data) and methods (functions) that the objects created from the class will have.
- Object: A specific instance of a class with actual values for the attributes and the ability to perform the
methods defined by the class.

Example:

#include <iostream>
using namespace std;

class MyClass {
public:
int Data=5;

int getData() {
return Data;
}
};

int main() {

MyClass obj;

cout << "Data: " << obj.getData() << endl;

return 0;
}

11. What is local class ? explain with example.

A local class is a class defined within a block of code, such as within a function, loop, or conditional block.
These classes are scoped to the block in which they are defined and cannot be accessed outside of it. Local
classes can access the local variables of the enclosing function, provided the variables are passed to the class
methods.

Example-

class OuterClass {
public:
void someMethod()
{
// Local class defined within a method
class LocalClass
{
public:
void display()
{
cout << "This is a local class." << endl;
}
};
// Creating an instance of the local class and calling its method
LocalClass localInstance;
localInstance.display();
}
};

int main() {
OuterClass outer;
outer.someMethod();
return 0;
}

Benefits of Using Local Classes(Not needed):

1. Organized Code: They help keep the code organized by confining certain logic to where it's used.
2. Improved Readability: Local classes make it clear that the class is only relevant within the context of
the function or block.
3. Encapsulation: By keeping the class local, you prevent it from being used elsewhere, which can
reduce errors and enhance security.

12. When you declare a member of a class static? Explain with example.

A static member of a class is a member that is shared among all instances of that class. This means that all
instances of the class share the same variable or method, rather than each instance having its own copy. Static
members belong to the class itself rather than to any particular object of the class.

When to Declare a Member Static-

Shared Data: When a variable needs to be shared across all instances of a class.

Utility Functions: Methods that do not need to access instance-specific data can be declared static.

Constants: Constants that are common across all instances can be declared static.

Example-
#include <iostream>
using namespace std;

class MyClass {
public:
static int staticVariable;
};

// Initialize static member outside the class


int MyClass::staticVariable = 0;

int main() {
MyClass m1, m2;
// Accessing and modifying static member through class
MyClass::staticVariable = 5;
cout << "Obj1 value: " << m1.staticVariable << endl; // Output: 5
cout<< "Obj2 value: "<< m2.staticVariable<<endl;

return 0;
}
Output: Obj1 value: 5
Obj2 value: 5

13. Define and explain friend function. When do we declare a function as friend function?

Friend function: A friend function of a class is defined outside that class' scope but it has the right to access
all private and protected members of the class. Even though the prototypes for friend functions appear in the
class definition, friends are not member functions.
To declare a function as a friend of a class, precede the function prototype in the class definition with
keyword friend as follows –

friend return_type functionName (Class name &obj); // Declaration of friend function

Situation when declare a function friend function


In the following situations friend function can be useful :

1. When certain operator overloading is required, friend function can be useful.

2. Friend function makes the creation of some types of I/O functions easier.

3. Sometimes two or more classes may contain interrelated members which may need to be operated at a time.
In such times a friend function is required.

14. What is friend function? Show with suitable code segment how friend function can be
defined.

A friend function in is a function that is not a member of a class but has access to its private and protected
members. To declare a friend function, we use the `friend` keyword within the class.

Example of a Friend Function:

#include <iostream>

using namespace std;

class MyClass {
private:
int privateMember = 10;

public:
// Friend function declaration
friend void displayFriend(MyClass &obj);
};

// Friend function definition


void displayFriend(MyClass &obj) {

cout << "Private Member: " << obj.privateMember << std::endl;


}
int main() {
MyClass obj;
displayFriend(obj); // Calling the friend function
return 0;
}
15. Write down the advantages and Disadvantages of using friend function.

Advantages of Friend Functions

 A friend function is able to access members without the need of inheriting the class.
 The friend function acts as a bridge between two classes by accessing their private data.
 It can be used to increase the versatility of overloaded operators.
 It can be declared either in the public or private or protected part of the class.

Disadvantages of Friend Functions

 Friend function have access to private members of a class from outside the class which violates the
law of data hiding.
 Breach of data integrity.
 Conceptually messy.
 Cannot do any run time polymorphism in its members.

16. Drawback of friend function?

1. Friend function have access to private members of a class from outside the class which violates the law of
data hiding.
2. Breach of data integrity.
3. Conceptually messy.
4. Cannot do any run time polymorphism in its members.

17. Define static data member with example.

It is a variable which is declared with the static keyword, it is also known as class member, and thus only
single copy of the variable creates for all objects. All static data is initialized to zero when the first object is
created, if no other initialization is present. We can't put it in the class definition but it can be initialized
outside the class using the scope resolution operator (::).
Declaration

static data_type member_name;

It should be defined outside of the class following this syntax:

data_type class_name :: member_name =value;

Example (Not needed):


#include <iostream>
using namespace std;
class Demo
{
private:
static int X; //Declaration
public:
static void fun()
{
cout <<"Value of X: " << X << endl;
}
};

int Demo :: X =10; //defining


int main()
{
Demo X;
X.fun();
return 0;
}

18. Mention the properties of static member functions.


Following are some properties of Static Member Function

1. A static member function can only have access to other static data members and functions declared in
the same class.
2. A static member function can be called using the class name with a scope resolution operator instead
of object name.
3. Global functions and data may be accessed by static member function.
4. A static member function does not have a this Pointer.
5. There cannot be a static and a non-static version of the same function.
6. They cannot be declared as const or volatile.
7. A static member function may not be virtual.

19. What is Forward Declaration? Why we use Forward Declaration?

Forward declaration is a technique used in programming, particularly in languages like C and C++, to declare
the existence of a class, function, or variable before it is defined or implemented. It provides a prototype of the
entity without giving its complete implementation details.

Here's why we use forward declaration:

1. Reduce Compilation Dependencies: By allowing entities to be declared without including their complete
implementation details, it minimizes compile-time dependencies.

2. Resolve Circular Dependencies: It helps break circular dependencies between classes or functions.

3. Improve Header File Efficiency: By reducing the number of header files included in other files, it
enhances header file management and compilation efficiency.

4. Avoid Unnecessary Include Chains: It prevents unnecessary inclusion of header files, keeping the
dependency chain shorter and more manageable.

5. Minimize Code Pollution: By separating implementation details from the interface, it keeps the codebase
cleaner and more maintainable.
20. Mention the special characteristics of friend function.
Characteristics of friend function
 Friend function is not in the scope of the class in which it has been declared as friend.

 It cannot be called using the object of the class as it is not in the scope of the class.
 It can be called similar to a normal function without the help of any object.
 Unlike member functions, a friend function cannot access the member variables directly and has to
use an object name and dot membership operator with each member variable.
 It can be declared either in the public or private scope area of a class.
 Usually, it has objects as arguments.

21. “Forward declaration is needed in case of using friend function”- justify your answer.

When we use a function as a friend between two classes, then we need forward declaration. As an example the
function max() is a friend of both class A and B. the function max() has argument from both A and B. The
compiler will not acknowledge the presence of B unless it’s name is declared in the beginning as below.

Class A
{
int data;
public:
friend void max(A x, B y);
};

Class B
{
int value;
public:
friend void max(A x, B y);
};

22. Write a program showing the use of data members.

#include <iostream>
using namespace std;
class Demo
{
private:
static int X; //Declaration
public:
static void fun()
{
cout <<"Value of X: " << X << endl;
}
};
//defining
int Demo :: X =10;
int main()
{
Demo X;
X.fun();
return 0;
}
Output: Value of X: 10

23. Write a program that swapping private data of classes using friend function.

#include <iostream>
using namespace std;
class B;
class A
{
int data;
public:
void put(int d)
{
data=d;
}
void display()
{
cout<<"Value of A:"<< data<<endl;
}
friend void swap(A &x, B &y);
};

class B
{
int data;
public:
void put(int d)
{
data=d;
}
void display()
{
cout<<"Value of B:"<< data<<endl;
}
friend void swap(A &x, B &y);
};

void swap(A &x, B &y)


{
int tmp;
tmp=x.data;
x.data=y.data;
y.data=tmp;
}

int main()
{
A a;
B b;
int x,y;
cout<< "Enter value 1: ";
cin>> x;
cout<< "Enter value 2: ";
cin>> y;
a.put(x);
b.put(y);
swap(a,b);
a.display();
b.display();

return 0;
}

Output: Enter value 1: 5


Enter value 1: 6
Value of A: 6
Value of A: 5

24. Describe the mechanism for accessing data members and member functions in the
following case-
1. Inside the main program.
2. Inside a member function of same class.
3. Inside the member function of another class.
Inside the main program: Inside the main program we can access data member and member function using
object and dot (.) operator. We know that private data cannot access from inside the main program.

Example code of- Q4

Inside a member function of same class: We can access the date member inside the same class just like
accessing a local variable of a function.

Example code of- Q5

Inside a member function of another class: If a member function of another class is a friend of the desired
class, it can access private and protected data members and member functions of that class.
Example:
class ClassA;
class ClassB {
private:
int privateData;
void privateFunction();
friend class ClassA; // Declare ClassA as a friend class
};
class ClassA {
public:
void accessClassB(ClassB &b) {
b.privateData = 20; // Accessing private data member
b.privateFunction(); // Accessing private member function
}
};

You might also like