Classes
Anonymous contributor
Published Jun 4, 2021Updated Nov 23, 2024
Contribute to Docs
A C++ class is a blueprint for creating objects that combines data attributes and functions to define the behavior and state of an entity.
class Person {
// Class members
};
Class Members
A class is comprised of class members:
- Attributes, also known as member data, consist of information about an instance of the class.
- Methods, also known as member functions, are functions that can be used with an instance of the class.
class City {// Attributeint population;public:// Methodvoid add_resident() {population++;}};
Access Control Operators
C++ classes have access control operators that designate the scope of class members:
public
members are accessible everywhere.private
members can only be accessed from within the same instance of the class or from friends classes.
class City {int population;public:void add_resident() {population++;}private:bool is_capital;};
Overloading
Redefining operators to work differently with custom data types is called operator overloading in C++. This enables the user to use these operators with objects of their own classes.
The following overloads the +
and ==
operators:
#include <iostream>using namespace std;class Point {public:int x;int y;public:Point(int x = 0, int y = 0) : x(x), y(y) {}Point operator+(const Point& other) const {return Point(x + other.x, y + other.y);}bool operator==(const Point& other) const {return (x == other.x) && (y == other.y);}void display() const {std::cout << "Point(" << x << ", " << y << ")\n";}};int main() {Point point1(3, 4);Point point2(1, 2);Point sum = point1 + point2;sum.display();Point point3(5, 2);Point point4(3, 6);bool isEqual = (point3 == point4);std::cout << "Points are equal: " << (isEqual ? "true" : "false") << "\n";}
This will output:
Point(4, 6)Points are equal: false
All contributors
- Anonymous contributor
- krushnarout
- Christine_Yang
- garanews
- christian.dinh
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C++ on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn C++
Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.Beginner Friendly11 hours