Q:

Demonstrate Example of public data members in C++

belongs to collection: C++ Classes and Object programs

0

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.

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program:

#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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C++ Classes and Object programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Create a class Point having X and Y Axis with gett... >>
<< Const Member Functions in C++...