Home » C++ programs » C++ Class and Objects programs

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

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.


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.


#include <iostream>
using namespace std;

class Numbers
        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;


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


Comments and Discussions



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© some rights reserved.