Different behavior of C++ with default value for public vs private scope

classes in c++ example program
openmp default(private)
powershell set variable
programming questions on classes and objects in c++
object oriented programming c++ examples
powershell script variable
openmp firstprivate
class and object in c++

I have two questions

1) Why can we give default value if the member is public but when it is private we are not allowed? Take below example:

#include <iostream>
using namespace std;
class Test
{
private:
    int a=5;
public:
    Test()
    {
        cout<<a<<endl;
        cout<<"default const";
        a=0;
    }

};
int main()
{
    Test x;
    cout<<x.a;

}

We get below error for this:

Compile Errors :
prog.cpp: In function 'int main()':
prog.cpp:6:11: error: 'int Test::a' is private
     int a=5;
           ^
prog.cpp:19:13: error: within this context

Whereas if I make it public as below:

#include <iostream>
using namespace std;
class Test
{ 
public:
    int a=5;
    Test()
    {
        cout<<a<<endl;
        cout<<"default const";
        a=0;
     }

};
int main()
{
    Test x;
    cout<<x.a;

}

We get output as :

5
default const0

2) My next question is, why do we have this behavior? Also when we provide this default value, why constructor value overrides the default value provided in class?

  1. The member is private, you get the error where you're trying to print it, outside of the class.

  2. Simple enough, first all of the default values are assigned (constructed, see comment), then the code inside the constructor is executed. That's why you see the 5 inside the constructor.

If you want the constructor to change the initialization value of a, you can use an initializer list:

Test(): a{0}
{
    cout<<a<<endl;
    cout<<"default const";
}

And this would print 0, the value of a will never be 5 when using this constructor.

Object-oriented Programming (OOP) in C++, Different behavior of C++ with default value for public vs private scope Browse other questions tagged c++ constructor default-value or ask your own question. A public member is accessible from anywhere outside the class but within a program. You can set and get the value of public variables without any member. A private member variable or function cannot be accessed, or even viewed from outside the class. Only the class and friend functions can access private members.

We can assign the value to the private member variables as well but it seems that you are accessing private member variable a outside of class which is not allowed.

Set-Variable, In other words, OOP combines the data structures and algorithms of a Member Functions (or methods, behaviors, operations): contains the dynamic There are two sections in the class declaration: private and public , which will In C++, you can specify the default value for the trailing arguments of a 2.11 "public" vs. Example of public, protected and private inheritance in C++. In the above example, we observe the following things: base has three member variables: x, y and z which are public, protected and private member respectively. publicDerived inherits variables x and y as public and protected.

The error message is a little misleading; the problem is with your usage. The declaration has been shown to you for context, and because the declaration happens to include an initialiser it looks like the error is about that initialisation. But it isn't.

So, we don't have that behaviour.

As for why assigning a value to the member "overrides" your initialised value, well, that's what assigning does. When you initialise something it gets a value, then when you assign to it later, now it has that value instead. It's the same as a simple local variable:

int x = 42;
x = 3;

What value does x hold now?

The code in the constructor's body is "later". By the time it fires, all member initialisations (be they default, or with values you've provided) have already completed.

Constructors (C++), The Set-Variable cmdlet assigns a value to a specified variable or changes the current PS C:\> Set-Variable -Name "desc" -Value "A description" PS C:\> Example 3: Understand public vs. private variables The sample output shows the difference in the behavior of public and private variables. Default value: False. The access level for class members and struct members, including nested classes and structs, is private by default. interfaces default to internal access. Delegates behave like classes and structs.

To (2), and specifically the "why": in-class initializers act as a default that are not dependant on any input passed to constructors, whereas constructor initializers can be seen as a specialization. Imagine a class with 10 contructors, all require the same static value for x, you should stick to in-class initializers to avoid redundant code.

18 OpenMP topic: Controlling thread data, class Box { public: // Default constructor Box() {} // Initialize a Box with equal m_height; } private: // Will have value of 0 when default constructor is called. const Box& other); // Additional parameters OK if they have default values using statement in /std:c++17 mode brings into scope all constructors from  The private Members. A private member variable or function cannot be accessed, or even viewed from outside the class. Only the class and friend functions can access private members. By default all the members of a class would be private, for example in the following class width is a private member, which means until you label a member,

Conceptual Modeling -- ER 2003: 22nd International Conference on , In a parallel region there are two types of data: private and shared. Sometimes this global update is what you want; in other cases the variable is intended Thus, you should not rely on any initial value, or on the value of the outer In both C and Fortran you can declare these variables private in the parallel for directive. Enumeration members are always public, and no access modifiers can be applied. Delegates behave like classes and structs. By default, they have internal access when declared directly within a namespace, and private access when nested. C# language specification. For more information, see the C# Language Specification. The language specification is the definitive source for C# syntax and usage.

C++ Core Guidelines, While UML can model both the static structure and the dynamic behavior of that define its domain type, its scope, and possibly a set of initial values. A method, on the other hand, the access modifiers (private, public, and protected), the class-​wide modifiers (static) A schema, S, is defined as a finite set of classes, < C >. An access modifier restricts the access of a class, constructor, data member and method in another class. In java we have four access modifiers: 1. default 2. private 3. protected 4. public. 1. Default access modifier. When we do not mention any access modifier, it is called default access modifier. The scope of this modifier is limited to the package only.

Access Control, By “modern C++” we mean effective use of the ISO C++ standard Controlling the behavior of a function through a global (namespace scope) variable (a are relatively rare compared to pointer-passing APIs, so the default is class widget::​impl { int n; // private data public: void draw(const widget& w) { /* . When an argument is omitted in a function call, the default value of that argument is automatically inserted by the compiler and passed in the function call. c. Default values can be constants. Default values cannot be global variables of function calls.

Comments
  • The error you see is not in the class constructor and has nothing to do with default values. The error happens in the expression cout << x.a. And it demonstrates the entire purpose of public/private access control.
  • Because you're trying to access it from main, the compiler is just telling you which variable declaration is the problem (it just happens to include initialisation).
  • A meta comment: This question isn't about "different behaviour": since one of the two examples is ill-formed, it isn't valid C++ and doesn't "behave" at all. "Different behaviour" usually means that two things both compile and run, but produce different observable effects given the same inputs.
  • Possible duplicate of What are public, private and protected in object oriented programming?
  • I don't think that's the actual, complete, error message from your compiler.
  • "default values are assigned" - nope, default values are not assigned (default values are constructed). You can see it here coliru.stacked-crooked.com/a/26f3951020f96db3 It is small technicality, but i think it is worth to be mentioned.
  • Yeah, you're right. I edited my answer. I just wanted to keep the answer simple, but I suppose it should be as accurate as possible :P