Objects and functions in C++

C++ Objects and Functions

In C++, a function is a block of code that performs a specific task. Functions are a key feature of C++ and are used to organize and modularize code. On this page you will be understanding about Objects and Functions in C++.

In C++, an object is an instance of a class. When you define a class, you are defining a new data type. You can then create variables of that type, which are called objects.

Objects and functions in C++

Object and Function in C++

In C++, it is possible to define a class, its member functions, and create an object of that class all in one place. This is known as the “combined definition” style.

Here is an example of how Pass Object from a Function in C++:

Run
#include <iostream>

using namespace std;

class MyClass {
  public:
    int x;
    void setX(int val) {
      x = val;
    }
    int getX() {
      return x;
    }
};

int main() {
  MyClass obj;
  obj.setX(5);
  cout << obj.getX() << endl;
  return 0;
}

Output

5

This program defines a class MyClass with a data member x and two member functions setX() and getX(). It then creates an object of that class called obj and uses the member functions to set and get the value of x.

Objects in C++ are a key part of object-oriented programming (OOP). They allow you to encapsulate data and behavior into a single, self-contained entity.

Return Object from a Function in C++

Run
#include <iostream>

using namespace std;

class MyClass {
  public:
    int x;
    MyClass(int val) {
      x = val;
    }
    int getX() {
      return x;
    }
};

int main() {
MyClass obj(5);
cout << obj.getX() << endl;
return 0;
}

Output

5

In this example, the class MyClass is defined with a data member x and a constructor function that initializes x to a specified value. The object obj is created using the constructor function and the value 5. The getX() member function is then used to retrieve the value of x and print it to the console.

This style can be useful for simple programs where you only need to create a single object of a given class. It can make the code more compact and easier to read. However, for larger and more complex programs, it is often more appropriate to use the separate function definition style, where the class definition and the object definitions are kept in separate parts of the code.

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription