Course Content
C++ OOP
C++ OOP
Methods 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:
Example
Example
class Example { public: void Method(); };
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.
main
#include <iostream> class Example { public: void Method(); }; void Example::Method() { std::cout << "Method was called" << std::endl; }
Feel free to tackle the task using the method of your preference. But the common good practice is to separate declaration and implementation.
Swipe to show code editor
- 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.
Thanks for your feedback!
Methods 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:
Example
Example
class Example { public: void Method(); };
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.
main
#include <iostream> class Example { public: void Method(); }; void Example::Method() { std::cout << "Method was called" << std::endl; }
Feel free to tackle the task using the method of your preference. But the common good practice is to separate declaration and implementation.
Swipe to show code editor
- 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.
Thanks for your feedback!