by Dinesh Thakur Category: Classes in C++

1: Public, protected and private are three access specifier in C++. Public data members and member functions are accessible outside the class. Protected data members and member functions are only available to derived classes. Private data members and member functions can’t be accessed outside the class. However there is an exception can be using friend classes. Write a function that swaps the values of two integers, using int* as the argument type.


void swap(int* a, int*b) {

int t;

t = *a;

*a = *b;

*b = t;



Ans.2: class Point2D{

int x; int y;

public int color;

protected bool pinned;

public Point2D() : x(0) , y(0) {} //default (no argument) constructor


Point2D MyPoint;

You cannot directly access private data members when they are declared (implicitly)


MyPoint.x = 5; // Compiler will issue a compile ERROR

//Nor yoy can see them:

int x_dim = MyPoint.x; // Compiler will issue a compile ERROR

On the other hand, you can assign and read the public data members:

MyPoint.color = 255; // no problem

int col = MyPoint.color; // no problem

With protected data members you can read them but not write them: MyPoint.pinned = true;

// Compiler will issue a compile ERROR

bool isPinned = MyPoint.pinned; // no problem


About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.C.A, MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.

Related Articles