Demonstrate Example of public data members in C++

C++ | Example of public data members: Here, we are going to learn how to declare, initialize and access public data members in C++?
Submitted by IncludeHelp, on September 20, 2018 [Last updated : March 01, 2023]

Public Data Members

All variables of a class are known as "data members of a class" and the variables which are declared in the public section of a class are known as "public data members of a class".

Public data members can be accessed through object name directly outside of the class.

Example:

Here, we have a class named "Numbers" with two public data members a and b, we will provide the value to them inside the main() and access (print) them inside main() also.

C++ program to implement the public data members

#include <iostream>
using namespace std;

class Numbers {
public:
    int a;
    int b;
};

//Main function
int main()
{
    //declaring object to the class
    Numbers Num;
    
    //assign values to a and b
    Num.a = 100;
    Num.b = 200;
    
    //print the values
    cout << "Value of Num.a: " << Num.a << endl;
    cout << "Value of Num.b: " << Num.b << endl;

    return 0;
}

Output

Value of Num.a: 100
Value of Num.b: 200


Related Programs




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.