Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Methods of the Class | Fundamentals of OOP
C++ OOP

Methods of the ClassMethods of the Class

Understanding methods

Methods in a class are essentially just functions that are defined within the class. They are used to define the behaviors or actions that objects of the class can perform.

Example

Typical methods a class Car might include:

         accelerate()
         brake()
         honk()

Methods often manipulate the attributes of the class or perform operations that are relevant to the objects.

Implementation of methods outside the class

Methods can be defined outside the class declaration using the scope resolution operator (::). This is often done to separate the declaration in the header file from its implementation in the source file. Here's how you would do it:

h

Example.h

cpp

Example.cpp

It's not mandatory to create two distinct files for this purpose; you can achieve it within a single file, and in certain situations, it proves to be beneficial.

cpp

main.cpp

Feel free to tackle the task using the method of your preference. But the common good practice is to separate declaration and implementation.


Task

  • Implement area() and perimeter() methods in a Square class.
  • Call this methods using instance of the class in the main function.
  • Output the area and perimeter of the square object using methods you created.

Everything was clear?

Section 1. Chapter 5
toggle bottom row

Methods of the ClassMethods of the Class

Understanding methods

Methods in a class are essentially just functions that are defined within the class. They are used to define the behaviors or actions that objects of the class can perform.

Example

Typical methods a class Car might include:

         accelerate()
         brake()
         honk()

Methods often manipulate the attributes of the class or perform operations that are relevant to the objects.

Implementation of methods outside the class

Methods can be defined outside the class declaration using the scope resolution operator (::). This is often done to separate the declaration in the header file from its implementation in the source file. Here's how you would do it:

h

Example.h

cpp

Example.cpp

It's not mandatory to create two distinct files for this purpose; you can achieve it within a single file, and in certain situations, it proves to be beneficial.

cpp

main.cpp

Feel free to tackle the task using the method of your preference. But the common good practice is to separate declaration and implementation.


Task

  • Implement area() and perimeter() methods in a Square class.
  • Call this methods using instance of the class in the main function.
  • Output the area and perimeter of the square object using methods you created.

Everything was clear?

Section 1. Chapter 5
toggle bottom row
some-alt