• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1400
  • Last Modified:

Default private access in C++

Hi,

I know that the default access in C++ is private.  But why is the default constructor (compiler's constructor if we don't provide one) public?

Example:

class Dog
{
};

void main()
{
Dog fido;
}

If the default access is private, then why am I still able to instantiate an object of the Dog class?  Thanks.
0
Monica2003
Asked:
Monica2003
1 Solution
 
ghimirenirajCommented:
A default constructor is implicitly declared if you don't declare any
constructor of your own.  An implicitly declared default constructor
is public and inline.

That's how C++ comiler generates obj code.

--Niraj
0
 
MysidiaCommented:


> But why is the default constructor (compiler's constructor if we don't provide one) public?

Because it is defined to be that way as part of the C++ language, and default constructors
would be useless if it were not so.

The constructor will be public unless it appears in the class declaration and
in a section not labelled (or labelled with 'protected' or 'private').

When we say 'the default access is private', what is meant that the default access
of _things explicitly declared_ in the structured type.


By the way, default access for declared access is not always private, either.
i.e. If you had written

struct Dog {
};

int main() {
   Dog fido();
}

The default access for declared members would be public.

A 'class' is more or less just a struct where the default is private.

0

Featured Post

Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

Tackle projects and never again get stuck behind a technical roadblock.
Join Now