0
0
C++programming~5 mins

Data members and member functions in C++

Choose your learning style9 modes available
Introduction

Data members store information about an object. Member functions let the object do things or change its data.

When you want to keep track of an object's details, like a person's name or age.
When you want the object to perform actions, like printing its details or updating its data.
When organizing code to group related data and actions together.
When creating blueprints (classes) for objects in your program.
Syntax
C++
class ClassName {
  access_specifier:
    data_type dataMember;
    return_type memberFunction(parameters) {
      // function body
    }
};

Data members hold the object's state (information).

Member functions define what the object can do.

Examples
This class has a data member color and a member function honk() that prints a sound.
C++
class Car {
  public:
    std::string color;  // data member
    void honk() {  // member function
      std::cout << "Beep!" << std::endl;
    }
};
This class keeps age private and uses member functions to set and get the age.
C++
class Person {
  private:
    int age;  // data member
  public:
    void setAge(int a) {  // member function
      age = a;
    }
    int getAge() {
      return age;
    }
};
Sample Program

This program creates a Dog object named myDog. It sets the dog's name and then calls the bark() function to print a message.

C++
#include <iostream>
#include <string>
using namespace std;

class Dog {
  public:
    string name;  // data member
    void bark() {  // member function
      cout << name << " says Woof!" << endl;
    }
};

int main() {
  Dog myDog;
  myDog.name = "Buddy";  // set data member
  myDog.bark();  // call member function
  return 0;
}
OutputSuccess
Important Notes

Data members can be public or private. Private means only member functions can access them.

Member functions can change data members or perform actions using them.

Use public: to allow outside code to access members, private: to hide them.

Summary

Data members store information about an object.

Member functions let the object perform actions or change its data.

Together, they define what an object is and what it can do.