C++ Classes:
Class is the collection of similar objects which is defined as the blueprint to define attribute and behavior for all the object of class.
Syntax:
class class-name {
variable;
function;
};
Object
It is a real world entity having data and method.
Syntax:
class-name object-name;
Access specifier
In C++, access specifiers are keywords used to control the access levels of class members. They determine how different parts of your program can interact with the members of a class.
There are three main access specifiers in C++:
1) Private: Members declared as private are accessible only within the same class or from the friend functions. They are not accessible from outside the class, including derived classes. This specifier is used to hide the internal details of a class and to provide encapsulation.
2) Protected: They are used during inheritance. Members declared as protected are accessible within the same class, from derived classes, and from friend functions. They are not accessible from outside the class hierarchy.
3) Public: Members declared as public are accessible from anywhere in the program. They can be accessed through an object of the class using the dot operator.
Accessing data-member of class
Access of data member depends upon access control of that member. If the access control is public then the data member can be easily accesed using member access/ dot operator (.) with the object of class. If the data member is defined as private or protected then we can’t access data member directly.
Example: For accessing data member using public access control
#include <iostream>
class MyClass {
public:
int NepalEnotes;
};
int main() {
MyClass obj;
obj.NepalEnotes= 10;
std::cout << “Value of publicMember: ” << obj.NepalEnotes << std::endl;
return 0;
}
Example: For accessing data member using private access control
#include <iostream>
class nepalEnotes {
private:
int nexus;
public:
void setNexus(int value) {
nexus = value;
}
int getNexus()
{
return nexus;
}
};
int main() {
nepalEnotes nexus;
nexus.setNexus(10);
std::cout << “Value of nexus: ” << nexus.getNexus() << std::endl;
return 0;
}
Example: For accessing data member using protected access control
#include <iostream>
using namespace std;
class nepalEnotes {
protected:
int nexus;
public:
void setNexus(int value) {
nexus = value;
}
int getNexus()
{
return nexus;
}
};
int main() {
nepalEnotes nexus;
nexus.setNexus(10);
cout << “Value of nexus: ” << nexus.getNexus() << endl;
return 0;
}
Defining member function
The member function are the function having their declaration inside the class definition and works on data member of the class.
There are two ways to define member function:-
i) Defining member function inside the class
These functions are defined within the class definition and provide the ability to perform operations on the class’s data members and interact with other objects of the same class. Arguments can also be passed within the function.
Syntax: For defining function inside the class
return-type function-name( set of arguments with data types)
{
\\ function body;
}
Example: For defining member function inside the class
#include <iostream>
using namespace std;
class NepalEnotes {
public:
// Member function definition inside the class
void NexuCorner() {
cout << “Keep Learning From The Best Platform” << endl;
}
};
int main() {
NepalEnotes obj;
// Calling the member function NexuCorner inside the class
obj.NexuCorner();
return 0;
}
ii) Defining member function Outside the class
If a member function’s definition is outside the class declaration, it is treated as an inline function only if it is explicitly declared as inline . In addition, the function name in the definition must be qualified with its class name using the scope-resolution operator (:: ).
Syntax: For defining member function outside the class
Return_type class_name :: function_name (parameter_list) {
\\ function body;
}
Example: For defining member function outside the class
#include <iostream>
using namespace std;
// Class declaration
class NepalEnotes {
public:
// Function declaration
void NexuCorner();
};
// Function definition outside the class
void NepalEnotes::NexuCorner() {
cout << “Keep Learning From The Best Platform” << endl;
}
int main() {
NepalEnotes obj;
// Calling the member function obj.NexuCorner();
return 0;
}
Write a program in C++ to enter details of student using OOP concept
#include <iostream>
#include <string>
using namespace std;
class DurgaLaxmi {
private:
string name;
int rollNumber;
float fee;
string studentClass;
string studentID;
public:
// Member function to set student details
void setDetails(string n, int rn, float f, string cl, string id) {
name = n;
rollNumber = rn;
fee = f;
studentClass = cl;
studentID = id;
}
// Member function to print student details
void NepalEnotes() {
cout << “Student Name: ” << name << endl;
cout << “Roll Number: ” << rollNumber << endl;
cout << “Fee: $” << fee << endl;
cout << “Class: ” << studentClass << endl;
cout << “Student ID: ” << studentID << endl;
}
};
int main() {
DurgaLaxmi NexuCorner;
// Setting student details using member function
NexuCorner.setDetails(“John Doe”, 101, 500.0, “Grade 10”, “STU123”);
// Calling the member function NepalEnotes to print student details
NexuCorner.NepalEnotes();
return 0;
}
Constructor
A constructor in C++ is a special member function of a class that is automatically called when an object of that class is created. Its primary purpose is to initialize the object’s data members and perform any necessary setup tasks. Constructors have the same name as the class and no return type, not even void. It is used to create value for object.
Characteristics of Constructor:
Same Name as Class: Constructors have the same name as the class they belong to.
No Return Type: Constructors do not have a return type, not even void.
Called Automatically: Constructors are automatically called when an object of the class is created.
Initialization: Constructors are primarily used for initializing the object’s data members and performing any necessary setup tasks.
Can Be Overloaded: Like regular functions, constructors can be overloaded, meaning a class can have multiple constructors with different parameter lists.
Can Have Default Arguments: Constructors can have default arguments, allowing objects to be created with fewer arguments if needed.
Cannot Be Inherited or Overridden: Constructors cannot be inherited or overridden by derived classes. However, derived class constructors can call base class constructors.
No Explicit Return: Constructors do not have an explicit return statement. Once the constructor finishes execution, the object is considered initialized and ready for use.
Invoked Implicitly: Constructors are invoked implicitly when an object is created using the class name and optional arguments.
Initialization Lists: Constructors can use initialization lists to initialize data members directly, which can be more efficient than assignment in the body of the constructor.
Can Be Private: Constructors can be made private to prevent direct instantiation of objects, enforcing singleton or factory patterns.
There are 3 types of constructor:
1) Default Constructor: A default constructor in C++ is a constructor that doesn’t take any arguments. It’s called automatically when an object of the class is created without providing any initial values. Default constructors are provided by the compiler if no other constructors are explicitly defined in the class.
Syntax: For default constructor
class ClassName {
public:
// Default Constructor
ClassName() {
// Initialization code
}
};
Example: For default constructor
#include <iostream>
using namespace std;
class NepalEnotes {
public:
// Default Constructor
NepalEnotes() {
cout << “Nepal E-notes Platform For Easy And Effective Learning” << endl;
}
};
int main() {
// Creating an object of class NepalEnotes obj;
return 0;
}
2) Parameterized Constructor: A parameterized constructor is a constructor in object-oriented programming that allows you to initialize an object with specific values when it is created. It takes parameters as input and assigns those values to the instance variables of the object. This enables you to create objects with different initial states depending on the values passed to the constructor.
syntax:
class ClassName {
public:
// Parameterized constructor declaration
ClassName(type1 parameter1, type2 parameter2, …) {
// Constructor body
// Initialization of instance variables using parameters
}
};
Example: For parameterized constructor
#include <iostream>
#include <string>
using namespace std;
class NepalEnotes {
private:
string officeName;
string location;
int numOfEmployees;
public:
// Parameterized constructor
NepalEnotes(string name, string loc, int employees) {
officeName = name;
location = loc;
numOfEmployees = employees;
}
// Member function to display office details
void Nexus() {
cout << “Office Name: ” << officeName << endl;
cout << “Location: ” << location << endl;
cout << “Number of Employees: ” << numOfEmployees << endl;
}
};
int main() {
// Creating an object using the parameterized constructor
NepalEnotes office(“Nepal Enotes Pvt. Ltd.”, “Attariya”, 50);
// Displaying office details using the member function
cout << “Office Details:\n”;
office.Nexus();
return 0;
}
3) Copy Constructor: A copy constructor in C++ is a special constructor that initializes a new object as a copy of an existing object. It is invoked when a new object is created and initialized with the data of an existing object of the same class. The copy constructor allows you to create a new object with the same data as the existing object, effectively making a copy of it.
syntax:
class ClassName {
public:
// Copy constructor declaration
ClassName( ClassName &obj)
{
variable1=obj.variable1;
variable2=obj.variable2;
variable n=obj.variable n;
}
};
Example: For copy constructor
#include <iostream>
#include <string>
using namespace std;
class NepalEnotes {
private:
string message;
public:
// Default constructor
NepalEnotes() : message(“Be The Best By learning from the best”) {}
// Parameterized constructor
NepalEnotes(string msg) : message(msg) {}
// Copy constructor
NepalEnotes(NepalEnotes& other) : message(other.message) {}
// Member function Nexus
void Nexus() {
cout << “Nexus function called. Message: ” << message << endl;
}
// Member function Nexu
void Nexu () {
cout << “Nexu function called. Message: ” << message << endl;
}
};
int main() {
// Create an object
NepalEnotes obj1;
// Call Nexus function
obj1.Nexus();
// Create another object using copy constructor
NepalEnotes obj2 = obj1;
// Call Nexu function on the second object
obj2.Nexu();
return 0;
}
Constructor Overloading
Constructor overloading in C++ refers to the ability to define multiple constructors for a class, each with a different set of parameters. This allows objects of the class to be initialized in different ways, depending on the parameters passed during object creation. Constructor overloading provides flexibility in object initialization and can make code more readable and maintainable.
Example: for constructor overloading
#include <iostream>
#include <string>
using namespace std;
class DurgaLaxmi {
private:
string message;
public:
// Default constructor
DurgaLaxmi() {
message = “Default Message”;
}
// Parameterized constructor
DurgaLaxmi(string msg) {
message = msg;
}
// Copy constructor
DurgaLaxmi(DurgaLaxmi& other) {
message = other.message;
}
// Member function Nepal
void Nepal() {
cout << “Nepal function called. Message: ” << message << endl;
}
};
int main() {
// Using default constructor
DurgaLaxmi obj1;
obj1.Nepal();// Using parameterized constructor
DurgaLaxmi obj2(“Be The Best By learning from the best”);
obj2.Nepal();
// Using copy constructor
DurgaLaxmi obj3 = obj2;
obj3.Nepal();
return 0;
}
Destructor
Destructor is a special member function of a class that is automatically called when an object goes out of scope or is explicitly deleted using the delete keyword. The destructor has the same name as the class preceded by a tilde (~) symbol. It is used to release resources acquired by the object during its lifetime, such as dynamic memory allocations, file handles, database connections, etc.
Syntax:
class ClassName {
public:
// Constructor, member functions, etc.
// Destructor declaration
~ClassName() {
// Destructor body
// Cleanup code
}
};
Example: For Destructor
#include <iostream>
using namespace std;
class NexuCorner {
public:
// Constructor
NexuCorner() {
cout << “Constructor called” << endl;
}
// Destructor
~NexuCorner() {
cout << “Destructor called” << endl;
}
};
int main() {
cout << “Creating object…” << endl;
NexuCorner obj; // Constructor called
cout << “Object created.” << endl;
cout << “Exiting main…” << endl;
return 0;
}
Static Data Member
In C++, a static data member is a member of a class that belongs to the class itself rather than to individual objects of the class. This means that there is only one instance of the static data member shared among all objects of the class. It is declared using the ‘static’ keyword within the class
declaration.
Syntax:
class ClassName {
public:
static data_type staticDataMemberName;
};
Example: for static data member
#include <iostream>
using namespace std;
class NepalEnotes {
public:
static int count; // Declaration of static data member
NepalEnotes() {
count++; // Increment count each time an object is created
}
static void Nexus() {
cout << “Nexus function called. Count: ” << count << endl;
}
};
int NepalEnotes::count = 0; // Definition and initialization of static data member
int main() {
NepalEnotes obj1;
NepalEnotes obj2;
NepalEnotes obj3;
NepalEnotes::Nexus(); // Call static function Nexus
return 0;
}
Static Member Function
A static member function is a member function of a class that operates on class-level data rather than on specific objects of the class. It does not have access to the ‘this’ pointer, meaning it cannot access non-static member variables or call non-static member functions directly. Static member functions are called using the class name, not an object of the class. They are declared using the ‘static’ keyword within the class declaration.
Syntax:
class ClassName {
public:
static return_type functionName (parameters);
};
Example:
#include <iostream>
using namespace std;
class NepalEnotes {
private:
static int count;
public:
static void Nexus() {
cout << “Nexus function called. Count: ” << count << endl;
}
static void incrementCount () {
count++;
}
};
// Definition and initialization of static data member
int NepalEnotes::count = 0;
int main() {
NepalEnotes::incrementCount();
NepalEnotes::incrementCount();
NepalEnotes::incrementCount();
NepalEnotes::Nexus();
return 0;
}