C++ – First Class

C++ Class structure

Classes are a mechanism to build our own types.

  • Members of a class are private by default. They can be accessed inside a class, but not outside of class.

C++ class Syntax

The syntax for defining a C++ class typically looks like this:

class ClassName {
  private:
    // private members and functions go here
  public:
    // public members and functions go here
};

Let’s break this down:

  • class is a keyword that indicates we are defining a new class.
  • ClassName is the name of the class, which should be a meaningful name that describes the concept or object the class represents.
  • private: and public: are access specifiers that determine the visibility of the members and functions of the class. Members and functions declared as private are only accessible within the class itself, while members and functions declared as public can be accessed from outside the class.
  • Members of the class can include variables, functions, and other classes. Functions defined inside a class are called member functions.
  • The class definition typically ends with a semicolon (;) after the closing brace (}). This is similar to how you end a function or control structure block in C++.

Here is an example of a simple C++ class definition:

class Rectangle {
  private:
    int width, height;
  public:
    void setDimensions(int w, int h) {
      width = w;
      height = h;
    }
    int getArea() {
      return width * height;
    }
};

This class represents a rectangle, with private member variables for its width and height, and public member functions for setting the dimensions and getting the area.


The above design is bad. We have to keep member variables private.

Notes on Class members

Class data members can’t be references.

Why C++ data members can’t be references ?

C++ class data members cannot be references because references must always be initialized to refer to an existing object, and once initialized, they cannot be reassigned to refer to a different object.

In contrast, C++ class data members are typically initialized in the constructor of the class, and may be reassigned or modified later on during the lifetime of the object. References would not be suitable for this purpose, as they cannot be reassigned once initialized.

Additionally, it is important to note that when an object is copied or assigned, the value of a reference is copied, not the reference itself. This means that if a class contained a reference member, the default copy constructor and assignment operator would not correctly copy the reference. This can lead to unintended behavior and bugs.

For these reasons, C++ class data members are typically implemented as pointers or values, rather than references.