Difference Between Private and Protected Members of C++ Classes

What is the difference between private and protected members of C++ classes?

Private members are only accessible within the class defining them.

Protected members are accessible in the class that defines them and in classes that inherit from that class.

Edit: Both are also accessible by friends of their class, and in the case of protected members, by friends of their derived classes.

Edit 2: Use whatever makes sense in the context of your problem. You should try to make members private whenever you can to reduce coupling and protect the implementation of the base class, but if that's not possible then use protected members. Check C++ FAQ for a better understanding of the issue. This question about protected variables might also help.

What is the difference between protected and private?

private - only available to be accessed within the class that defines them.

protected - accessible in the class that defines them and in other classes which inherit from that class.

What is the difference between public, private, and protected inheritance in C++?

To answer that question, I'd like to describe member's accessors first in my own words. If you already know this, skip to the heading "next:".

There are three accessors that I'm aware of: public, protected and private.

Let:

class Base {
public:
int publicMember;
protected:
int protectedMember;
private:
int privateMember;
};
  • Everything that is aware of Base is also aware that Base contains publicMember.
  • Only the children (and their children) are aware that Base contains protectedMember.
  • No one but Base is aware of privateMember.

By "is aware of", I mean "acknowledge the existence of, and thus be able to access".

next:

The same happens with public, private and protected inheritance. Let's consider a class Base and a class Child that inherits from Base.

  • If the inheritance is public, everything that is aware of Base and Child is also aware that Child inherits from Base.
  • If the inheritance is protected, only Child, and its children, are aware that they inherit from Base.
  • If the inheritance is private, no one other than Child is aware of the inheritance.

What is the difference between public, protected, package-private and private in Java?

The official tutorial may be of some use to you.

















































ClassPackageSubclass
(same pkg)
Subclass
(diff pkg)
World
public+++++
protected++++
no modifier+++
private+

What are public, private and protected in object oriented programming?

They are access modifiers and help us implement Encapsulation (or information hiding). They tell the compiler which other classes should have access to the field or method being defined.

private - Only the current class will have access to the field or method.

protected - Only the current class and subclasses (and sometimes also same-package classes) of this class will have access to the field or method.

public - Any class can refer to the field or call the method.

This assumes these keywords are used as part of a field or method declaration within a class definition.

In C#, what is the difference between public, private, protected, and having no access modifier?

Access modifiers

From docs.microsoft.com:

public

The type or member can be accessed by any other code in the same assembly or another assembly that references it.

private

The type or member can only be accessed by code in the same class or struct.

protected

The type or member can only be accessed by code in the same class or struct, or in a derived class.

private protected (added in C# 7.2)

The type or member can only be accessed by code in the same class or struct, or in a derived class from the same assembly, but not from another assembly.

internal

The type or member can be accessed by any code in the same assembly, but not from another assembly.

protected internal

The type or member can be accessed by any code in the same assembly, or by any derived class in another assembly.

When no access modifier is set, a default access modifier is used. So there is always some form of access modifier even if it's not set.

static modifier

The static modifier on a class means that the class cannot be instantiated, and that all of its members are static. A static member has one version regardless of how many instances of its enclosing type are created.

A static class is basically the same as a non-static class, but there is one difference: a static class cannot be externally instantiated. In other words, you cannot use the new keyword to create a variable of the class type. Because there is no instance variable, you access the members of a static class by using the class name itself.

However, there is a such thing as a static constructor. Any class can have one of these, including static classes. They cannot be called directly & cannot have parameters (other than any type parameters on the class itself). A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced. Looks like this:

static class Foo()
{
static Foo()
{
Bar = "fubar";
}

public static string Bar { get; set; }
}

Static classes are often used as services, you can use them like so:

MyStaticClass.ServiceMethod(...);

what is the difference between protected and private protected in c#?

It's about the acces modifier. More specific: inheritance and multiple assemblies. Consider the following:

For normal protected (explained with along private):

class Base
{
private bool X;
protected bool Y;
}

class A : Base
{
public void Foo()
{
X = false; //error: cannot access private member.
Y = true; //can access protected member, but only from classes with `: Base`
}
}

class B
{
public void Foo()
{
A a = new A();

a.X = false; //error: cannot access private member.
a.Y = false; //error: cannot access protected member.
}
}

Now the difference with private protected is that it must live in the same assembly to be accessible:

So:

class A : Base
{
public void Foo()
{
X = false; //error: cannot access private member.
Y = true; //can access protected member, but only from classes with `: Base` AND
//they need to be defined in the same assembly as Base
}
}

Is valid, but only if both A and Base are compiled in the same assembly/dll/exe etc.


Now, since that clear, when would you use an actual private protected?

A lot can be said about this. Some (including me) would argue that the use of private protected is an anti-pattern, because in my oppinion it's closly related to the friend keyword. And I must say, although in contradiction to friend, private protected keeps "the dirt" isolated, it still is arbitrary behavior, logic, depending on the location of it's definition.

Having said that the question remains, when to use it. You might be surprised I punctually used it once, and it was quite helpful.

Consider the following case:

  • Having a conceptual, decorator pattern styled code base, for example some graphical object system.
  • All the objects will be "renderable", in various ways.
  • Because you have a lot, it comes in handy to create a base class which only you are using for convinience.
  • You don't want to let other user be using this functionality, since it's not well documented and really specifi to your implementation
  • The classes themselves are public.

.... then I would use private protected ;-)

What is the difference between private and protected Internal?

  • A protected internal member is visible to any code in the current assembly or in a derived class in another assembly. In technical words, it's the logical disjunction of protected and internal.
  • A private member is visible only to code in the same class.

protected internal is actually the second most permissive access modifier after public.


It's worth noting that protected is arguably more permissive than internal, since it allows access from code that you have no control over (i.e. other assemblies). While internal allows access from all code in the current assembly, this code is yours and you have control over it!

To paraphrase, protected (and protected internal) members are part of the public API of your assembly (and should therefore be documented). internal members are not.

C++ why use public, private or protected inheritance?

Use public inheritance to reflect an is-a relationship. This is the main use for inheritance, especially in combination with virtual functions. It allows re-use of interface, not just of old code by new code, but also re-use of new code by old code! (because of virtual function dispatch at runtime).

In exceptional circumstances, use private inheritance to reflect an is-implemented-in-terms-of relationship. This is a commonly overused pattern, often the equivalent goal can be reached through composition (having the would-be base class as a data member). Another drawback is that you can easily have multiple inheritance of the same base class (twice or more removed) leading to the so-called Diamond Problem.

Avoid using protected inheritance, it suggest that your class interface is client-dependent (derived classes versus the world). Often this is due to classes having multiple responsiblities, suggesting a refactoring into separate classes is appropriate.

How to choose between private and protected access modifier to encapsulate members between base and childs classes?

Why don't I have an error message, when I set ID value in daughter class, the sentence this.id=value is executed, but how can can I access to it from my child class if it is private?

When you call a public method on a class, that method can access private members of that class:

public class Foo
{
public void Bar()
{
Baz();
}

private void Baz()
{
// private method called by public method
}
}

var foo = new Foo();
foo.Bar();

This compiles just fine. Your setter is the same: it's public, so callable from everywhere, even if it accesses private members.

As for making your field (private long id = -1;) protected: yes, that will mean you can access it in derived classes. But whether you want to is another question.

You have declared a public property for a reason. Perhaps you want to do some validation in its setter or getter. If not, if you're just using a property to access a private field, you could just ditch the entire private field and use an auto-implemented property:

public long ID { get; set; } = -1;

Then you can access the property everywhere, from within itself, from derived classes and from code using this class.

See also:

  • What is the difference between a field and a property?
  • What are Automatic Properties in C# and what is their purpose?


Related Topics



Leave a reply



Submit