A class in C++ is a blueprint for creating objects. It encapsulates data for the object and methods to manipulate that data.
A class is defined using the class
keyword followed by the class name and a body enclosed in curly braces.
An object is an instance of a class. It is created by declaring it with the class type.
Access modifiers define the access level of class members. C++ has three: public
, private
, and protected
.
Constructors are special member functions used to initialize objects. They have the same name as the class.
Destructors are used to release resources allocated to an object. They have the same name as the class prefixed with a tilde (~).
class Car {
public:
string brand;
string model;
int year;
Car(string x, string y, int z) {
brand = x;
model = y;
year = z;
}
};
// Create an object of Car
Car carObj1("Toyota", "Corolla", 2015);
cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year;
Methods are functions defined inside a class. They operate on the data contained in the object.
Static members are shared among all objects of a class. They can be accessed using the class name.
Friend functions have access to private and protected members of a class. They are not member functions.
Inheritance allows a class to inherit properties and methods from another class. It promotes code reusability.
Polymorphism allows methods to do different things based on the object it is acting upon. It is implemented using function overloading and overriding.
Encapsulation is the bundling of data and methods that operate on the data within a single unit or class.
Console Output:
Toyota Corolla 2015
Constructors are used to initialize objects. They set initial values for object attributes.
There are three types of constructors: default, parameterized, and copy constructors.
Destructors clean up resources that an object may have acquired during its lifetime.
Constructors and destructors are automatically called when an object is created and destroyed, respectively.
class Rectangle {
public:
int width, height;
Rectangle(int w, int h) {
width = w;
height = h;
}
~Rectangle() {
cout << "Rectangle destroyed";
}
};
Rectangle rect(10, 20);
cout << rect.width << " " << rect.height;
Multiple constructors can be defined with different parameters to initialize objects in different ways.
Destructors cannot be overloaded and do not take parameters. They are called once per object.
Console Output:
10 20
Rectangle destroyed
Inheritance allows one class to inherit members and behaviors from another class, promoting code reusability.
The class that is inherited from is called the base class, and the class that inherits is called the derived class.
C++ supports several types of inheritance: single, multiple, multilevel, hierarchical, and hybrid inheritance.
Access control determines how members of the base class can be accessed by the derived class.
class Animal {
public:
void eat() {
cout << "Eating";
}
};
class Dog : public Animal {
public:
void bark() {
cout << "Barking";
}
};
Dog myDog;
myDog.eat();
myDog.bark();
Virtual inheritance is used to solve the diamond problem in multiple inheritance scenarios.
Constructors and destructors of base and derived classes are called in a specific order during object creation and destruction.
Console Output:
Eating
Barking
Polymorphism allows methods to perform different tasks based on the object calling them.
Also known as static binding, it is achieved through function overloading and operator overloading.
Also known as dynamic binding, it is achieved through virtual functions and inheritance.
Virtual functions allow derived classes to override methods of the base class, enabling dynamic method resolution.
class Base {
public:
virtual void show() {
cout << "Base class";
}
};
class Derived : public Base {
public:
void show() override {
cout << "Derived class";
}
};
Base* b;
Derived d;
b = &d;
b->show();
A pure virtual function is declared by assigning 0 to it and makes a class abstract.
Classes containing pure virtual functions are abstract and cannot be instantiated.
Console Output:
Derived class
Encapsulation is the bundling of data and methods that work on that data within a single unit.
It helps protect the internal state of an object and only allows manipulation through methods.
Getters and setters are methods used to access and update private data members of a class.
Encapsulation helps in hiding the internal implementation details of a class from the outside world.
class Employee {
private:
int salary;
public:
void setSalary(int s) {
salary = s;
}
int getSalary() {
return salary;
}
};
Employee emp;
emp.setSalary(50000);
cout << emp.getSalary();
Encapsulation is crucial for designing robust interfaces and ensuring that objects are used in a controlled manner.
By hiding complexities, encapsulation makes code easier to maintain and modify.
Console Output:
50000
Operator overloading allows operators to be redefined and used in different ways, particularly with user-defined types.
Operators are overloaded by defining a function with the operator
keyword followed by the operator symbol.
Common operators that can be overloaded include +, -, *, /, ==, and [] among others.
Not all operators can be overloaded. For instance, the scope resolution (::) and member selection (.) operators cannot.
class Complex {
private:
int real, imag;
public:
Complex(int r = 0, int i = 0) { real = r; imag = i; }
Complex operator + (Complex const &obj) {
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}
void display() { cout << real << " + i" << imag; }
};
Complex c1(10, 5), c2(2, 4);
Complex c3 = c1 + c2;
c3.display();
Binary operators require two operands and are overloaded by defining a member function with one parameter.
Unary operators take a single operand and are overloaded by defining a member function with no parameters.
Console Output:
12 + i9
Friend functions allow access to private and protected members of a class from outside the class.
Friend functions are declared using the friend
keyword inside the class definition.
They provide more flexibility in designing interfaces that need access to class internals.
Excessive use of friend functions can break the encapsulation principle of object-oriented programming.
class Box {
private:
int width;
public:
Box(int w) : width(w) {}
friend void printWidth(Box b);
};
void printWidth(Box b) {
cout << "Width of box: " << b.width;
}
Box box(10);
printWidth(box);
Entire classes can be declared as friends, allowing all member functions of the friend class to access private members of the befriended class.
Friendship is not inherited, meaning derived classes do not inherit the friend status of their base class.
Console Output:
Width of box: 10
Templates allow functions and classes to operate with generic types, making them flexible and reusable.
Function templates enable functions to work with different data types without being rewritten for each type.
Class templates allow classes to handle any data type, providing a way to create generic classes.
Templates are defined using the template
keyword followed by template parameters in angle brackets.
template
T add(T a, T b) {
return a + b;
}
cout << add(3, 4);
cout << add(3.5, 4.5);
Template specialization provides a way to define different implementations of a template for specific data types.
Templates can also accept non-type parameters, allowing more flexibility in template usage.
Console Output:
7
8
Newsletter
Subscribe to our newsletter for weekly updates and promotions.
Wiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterCompany
About usCareersPressCompany
About usCareersPressCompany
About usCareersPressLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesCompany
About usCareersPressCompany
About usCareersPressCompany
About usCareersPressLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesAds Policies