C++ Classes Unleashed: OOP Excellence For Beginners to Masters - w9school

Dive into C++ classes for unparalleled Object-Oriented Programming. Unleash coding excellence, master encapsulation, and elevate your software design skills. Explore the essence of OOP now!

C++ Classes Unleashed: OOP Excellence For Beginners to Masters - w9school

C++ OOP

C++: What is OOP?

OOP is an acronym for Object-Oriented Programing.

Procedural programming involves writing functions or procedures which perform operations on data, whereas object-oriented programming is the creation of objects that can contain functions and data.

Object-oriented programming has many benefits over procedural programs.

  • OOP is quicker and simpler to carry out
  • OOP offers a clear and concise structure for programs
  • OOP helps keep C++ code clean. C++ code DRY "Don't Repeat Yourself", and makes the code simpler to modify, maintain and troubleshoot
  • OOP can be used to build fully reusable applications with less code, and reduce development time

Tips: The "Don't Repeat Yourself" (DRY) principle is to reduce the repeating of codes. You must remove code that is common to the application, then place them in a single location and reuse them instead repeating the same code.

C++: What are Classes and Objects?

Classification and object are two major elements of object-oriented programming.

Take a look at the image below to discover the differences between objects and classes:

Another illustration:

A class is an object template, and an object is a subset of the class.

When individuals are made they inherit all variables and functions of the class.

You'll learn details regarding subjects and classes during the chapter.

C++ Classes and Objects

C++ Classes/Objects

C++ is an object-oriented programming language.

All of the things in C++ is associated with objects and classes as well as their properties and techniques. For instance, in actual life, a car can be described as the definition of an objects. It has characteristics like the color and weight, and techniques that are used to drive it, for example and brake.

Methods and attributes are essentially the same as variables that are essentially variables and functions that belong to the classes. They are usually described as "class members".

The term "class" refers to a type of data that can be defined by the user that we can utilize in our programs, and it functions in the role of an object constructor or as a "blueprint" for creating objects.

Create a Class

For creating a class make use of to create a class, use the term "class" keyword:

Example

Create a class titled " MyClass":

class MyClass {       // The class
  public:             // Access specifier
    int myNum;        // Attribute (int variable)
    string myString;  // Attribute (string variable)
};

Example explained

  • It is the keyword class word is employed to build a class dubbed MyClass.
  • Public Keyword: The "public" keyword can be described as a access specifyor that states that the members (attributes and techniques) in the class can be accessed from any other source outside of the class. We will discuss accessibility specifiers later on.
  • Within the class, there's the integer variable myNum and the string variable myString. In the event that variables are created inside the class, they are known as attribute.
  • Then, you can end the definition of class with the semicolon ;.

Create an Object

When using C++, an object is created using an existing class. We already have created a class called MyClass and now we are able to use it in order to build objects.

To create an instance of MyClass to create an MyClass object, enter the class's name and then the name of the object.

To access the attributes of the class ( myNum and myString) you must use Dot Syntax ( .) on the object:

Example

Create an object named " myObj" and then access the attributes:

class MyClass {       // The class
  public:             // Access specifier
    int myNum;        // Attribute (int variable)
    string myString;  // Attribute (string variable)
};

int main() {
  MyClass myObj;  // Create an object of MyClass

  // Access attributes and set values
  myObj.myNum = 15; 
  myObj.myString = "Some text";

  // Print attribute values
  cout << myObj.myNum << "\n";
  cout << myObj.myString;
  return 0;
}

Multiple Objects

It is possible to create multiple objects from the same class:

Example

// Create a Car class with some attributes
class Car {
  public:
    string brand;   
    string model;
    int year;
};

int main() {
  // Create an object of Car
  Car carObj1;
  carObj1.brand = "BMW";
  carObj1.model = "X5";
  carObj1.year = 1999;

  // Create another object of Car
  Car carObj2;
  carObj2.brand = "Ford";
  carObj2.model = "Mustang";
  carObj2.year = 1969;

  // Print attribute values
  cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
  cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
  return 0;
}

C++ Class Methods

Class Methods

The methods are functions which belong in the same class.

It is possible to define a function that belong to a class:

  • Inside class definition
  • Outside class definition

In the next example, it is possible to define a method in the class, and give it the name " myMethod".

NOTE: You access methods similar to attributes. You do this by creating an object in the class applying the syntax dot ( .):

Inside Example

class MyClass {        // The class
  public:              // Access specifier
    void myMethod() {  // Method/function defined inside the class
      cout << "Hello World!";
    }
};

int main() {
  MyClass myObj;     // Create an object of MyClass
  myObj.myMethod();  // Call the method
  return 0;
}

In order to create a new function that is not part of the definition of a class it is necessary to declare it within the class, and afterwards define it out the class. This is accomplished by defining your class's name following by the scope resolution to:: operator followed by what the term is for your function:

Outside Example

class MyClass {        // The class
  public:              // Access specifier
    void myMethod();   // Method/function declaration
};

// Method/function definition outside the class
void MyClass::myMethod() {
  cout << "Hello World!";
}

int main() {
  MyClass myObj;     // Create an object of MyClass
  myObj.myMethod();  // Call the method
  return 0;
}

Parameters

You can also add parameters

Example

#include 
using namespace std;

class Car {
  public:
    int speed(int maxSpeed);
};

int Car::speed(int maxSpeed) {
  return maxSpeed;
}

int main() {
  Car myObj; // Create an object of Car
  cout << myObj.speed(200); // Call the method with an argument
  return 0;
}

C++ Constructors

Constructors

The constructor method in C++ is a specific technique to be automatically invoked when an object in an existing class is made.

To build a constructor apply exactly the same class name then use in parentheses ():

Example

class MyClass {     // The class
  public:           // Access specifier
    MyClass() {     // Constructor
      cout << "Hello World!";
    }
};

int main() {
  MyClass myObj;    // Create an object of MyClass (this will call the constructor)
  return 0;
}

Note: The constructor has the same name as the class, and it remains publicly accessible and doesn't have a return value.

Constructor Parameters

Constructors also have the ability to take parameters (just as regular functions) and can be beneficial for creating initial values for attributes.

The following classes include the brand, model and year attributes, as well as the constructor has various parameters. In the constructor, you set these attributes to be equal to the constructor's parameter ( brand=x, and so on). When we invoke our constructor (by creating an object from the class) we provide some parameters into the constructor which set the values of the attributes to match:

Example

class Car {        // The class
  public:          // Access specifier
    string brand;  // Attribute
    string model;  // Attribute
    int year;      // Attribute
    Car(string x, string y, int z) { // Constructor with parameters
      brand = x;
      model = y;
      year = z;
    }
};

int main() {
  // Create Car objects and call the constructor with different values
  Car carObj1("BMW", "X5", 1999);
  Car carObj2("Ford", "Mustang", 1969);

  // Print values
  cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
  cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
  return 0;
}

Like functions, constructors can be declared outside of the class. First declare the constructor inside the class. Then, define it outside the class by defining that the title of the class then an appropriate scope resolution (::) operator followed by its name (which is similar to it is the name of the class):

Example

class Car {        // The class
  public:          // Access specifier
    string brand;  // Attribute
    string model;  // Attribute
    int year;      // Attribute
    Car(string x, string y, int z); // Constructor declaration
};

// Constructor definition outside the class
Car::Car(string x, string y, int z) {
  brand = x;
  model = y;
  year = z;
}

int main() {
  // Create Car objects and call the constructor with different values
  Car carObj1("BMW", "X5", 1999);
  Car carObj2("Ford", "Mustang", 1969);

  // Print values
  cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
  cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
  return 0;
}

C++ Access Specifiers

Access Specifiers

As of now, you're already familiar with that "public" keyword, which appears in all our classes:

Example

class MyClass {  // The class
  public:        // Access specifier
    // class members goes here
};

A "public" keyword can be described as an access specifyor. Access specifiers define how elements (attributes as well as methods) within a given class will be accessible. In the above example these members will be public meaning that they are accessible and changed from outside the code.

What do we do if we want our members to be kept private and away from view?

Within C++, there are three access specifiers in C++:

  • public Members can be accessed to anyone outside of the class
  • private members are not able to be accessible (or seen) from outside of the class
  • protected members can't be accessible from outside of the class, but they can be accessed by inheriting classes. Learn more about inheritance in the future.

In the following example, we illustrate the difference between members of the public members and private members:

Example

class MyClass {
  public:    // Public access specifier
    int x;   // Public attribute
  private:   // Private access specifier
    int y;   // Private attribute
};

int main() {
  MyClass myObj;
  myObj.x = 25;  // Allowed (public)
  myObj.y = 50;  // Not allowed (private)
  return 0;
}

If you attempt to log in as the private members, the following error is triggered:

error: y is private

Note: It is possible to gain access to individuals who are private in a particular class by using public methods within that same class. Check out in the following chapter ( Encapsulation) on how you can do this.

Tips: It is considered an excellent method to mark your class's attributes confidential (as regularly as are able to). This can reduce the chances of you (or other people) to make mistakes in the code. This is also the primary component to this concept of the Encapsulation concept that you will be able to discover more about during the subsequent chapter.

Note: By default, the members of a class can be private when you don't provide an access specifier:

Example

class MyClass {
  int x;   // Private attribute
  int y;   // Private attribute
};

C++ Encapsulation

Encapsulation

The purpose the purpose of Encapsulation is to ensure the "sensitive" data is hidden from the view of the user. In order to achieve this, you have to declare the class variables and attributes as secret (cannot be obtained by anyone outside of the class). If you wish to allow others to access or alter the contents that a particular member has you should make it public access as well as setting methods.

Access Private Members

To gain access to an attribute that is private, you must make use of the private "get" and "set" methods:

Example

#include 
using namespace std;

class Employee {
  private:
    // Private attribute
    int salary;

  public:
    // Setter
    void setSalary(int s) {
      salary = s;
    }
    // Getter
    int getSalary() {
      return salary;
    }
};

int main() {
  Employee myObj;
  myObj.setSalary(50000);
  cout << myObj.getSalary();
  return 0;
}

Example explained

This pay feature can be private and has restricted access.

This public setSalary() method takes an input variable ( s) and assigns it to the salary attribute (salary = s).

Public method of gettingSalary() method returns the value of the private salary attribute.

In the main(), we create an object from the Employee class. We can now use to call the settingSalary() method to change an attribute private up to the value of 50000. Then, we use our findSalary() method on the object, returning the value.

Why Encapsulation?

  • It is recommended that you declare the class attribute confidential (as frequently as you are able to). Encapsulation allows for better control of your data since you (or other people) are able to alter one component of the code and not affect other components.
  • Data security is enhanced

The Importance of Classes in C++ Programming

C++ classes are the cornerstone of object-oriented programming languages like C#. Combining data and functions, they allow developers to build objects that can be used directly within code. A class can be seen as similar to a blueprint; its form and purpose being determined. Classes are sometimes also referred to as data structures.

Classes provide your code with a much more modular structure, helping you write more efficient programs and make them more manageable. This is particularly helpful when working on large projects. C++ programming language supports various classes such as: enum classes, default constructors, static constructors and templated classes to make coding simpler and more manageable.

Writing programs using an object-oriented style offers several benefits. These include increased performance, greater reusability and reduced bugs; as well as making the code simpler to understand and debug. An OO style often makes code easier to comprehend and debug; its main distinguishing feature being its ability to combine data and function into one entity - this makes c++ an OO programming language; class is its main concept behind this OO model and key to its success.

C++ classes are defined with the keyword class followed by one or more access modifiers that define how other functions interact with it and access its data members. To maximize encapsulation and protect data members from being accessed outside the class, classes should typically be made private as much as possible.

Accessing the member functions of a class can be accomplished using the dot operator (.). A class may contain public, protected, or private member functions; any function can only access them if declared as friends of that class or granted explicit access permission by it.

Classes may include special member functions known as constructors and destructors that are invoked when class objects are created; destructors are then invoked when classes go out of scope or are deliberately deleted from existence.

A class can contain both member functions and global methods, which are called by other functions - similar to C's void function - to call other functions within it. Normally, C++ compilers will attempt to inline global methods as much as possible for improved code performance.

Layout of non-POD classes in memory isn't mandated by C++ standard; however, many compilers use single inheritance and concatenation of fields to represent parent class types and child class fields in memory. This helps achieve performance comparable to that of languages with built-in complex types; however, this method can lead to lots of duplicate code in a program and should therefore be limited as much as possible in terms of number and length of global functions used within one code base.

For more information, Please visit Home

What's Your Reaction?

like

dislike

love

funny

angry

sad

wow