Object Functions

Lesson 29
Author : Afrixi
Last Updated : November, 2022
C++ - Programming Language
This course covers the basics of programming in C++.

In C++, an object function (also known as a member function) is a function that is defined within a class and can be called on an object of that class. Object functions are used to perform operations on an object’s data members or to provide behavior that is specific to the class.

Here’s an example of how object functions can be used in C++:

#include <iostream>
#include <string>

class Person {
public:
  // constructors
  Person() {
    name = "";
    age = 0;
  }
  
  Person(std::string n, int a) {
    name = n;
    age = a;
  }
  
  // object functions
  void setName(std::string n) {
    name = n;
  }
  
  void setAge(int a) {
    age = a;
  }
  
  std::string getName() {
    return name;
  }
  
  int getAge() {
    return age;
  }
  
private:
  std::string name;
  int age;
};

int main() {
  // create object using constructor
  Person p1("Alice", 25);
  
  // call object functions on the object
  p1.setName("Bob");
  p1.setAge(30);
  
  // print object data using object functions
  std::cout << "Name: " << p1.getName() << std::endl;
  std::cout << "Age: " << p1.getAge() << std::endl;
  
  return 0;
}

In this example, we define a Person class with two constructors and four object functions. The setName and setAge functions are used to set the name and age data members of an object, while the getName and getAge functions are used to retrieve the values of these data members.

In the main function, we create an object p1 of the Person class using the parameterized constructor. We then call the setName and setAge functions on the p1 object to change its name and age data members. Finally, we print the values of these data members using the getName and getAge functions.

Object functions are an essential part of object-oriented programming in C++, as they allow us to encapsulate behavior and data within a class, making our code more modular and easier to understand.