In C++ sometimes in class definition public members are declared at first and privates later. But the variables or data members are normally private and used by the public methods. So, in this case variables are used but not even declared yet. Thus the code become difficult to understand. But I found renowned programmers, sites or books to declare the private members later. Does anybody knows what is the reason?
I do things that way round since users of my class don't care about the private members, they're interested in the public API (i.e. how to use my class).
Also, in header files I'm generally just declaring member functions, rather than defining them, so I'm not accessing any private members anyway.
We read text from top to bottom, so the most relevant information should be at the top. In a class definition, that's the public interface.
Private members and implementation should be hidden from the header file. Putting the private member definitions at the bottom is a quick way to do so. Perhaps it is better to use the Pimpl idiom and hide the private part of your class in an internal struct.
Normally private members don't matter. If I'm looking at a class to determine how to use it somewhere else in code I don't care about it's internals so put private members at the bottom since i don't need to know about them. If I"m modifying a class then I'll take the time to find the private members and know they'll be at the bottom instead of having to skim the entire class.
We are like opposites: My Question
My reasoning is that when you are becoming familiar with a class it is more beneficial to first get introduced to the public interface then go deeper into the private members when you need to. If you start by looking at the private members, you have no context how they are used.
Agreed. Private members should be declared at bottom. The only good reason to declare private members first that i found, is when a function needs to get or return a custom data type, like: vector . The compiler will ask you about what kind of data is that.
But even, in that case i preffer to do:
{
private: /// advicing ofc theres more private below!
earlier declare just of the type
public:
private:
};
Related
When should I mark the static method of a specific class as private other than public?
What aspects should I consider when making such considerations.
What are the advantages for mark the static method as private?
Any simple example would be appreciated, which could help me fully understand this matter.
UPDATE:
As per this answer, which says that[emphasise mine]:
This function could easily have been made freestanding, since it doesn't require an object of the class to operate within. Making a function a static member of a class rather than a free function gives two advantages:
It gives the function access to private and protected members of any object of the class, if the object is static or is passed to the function;
It associates the function with the class in a similar way to a namespace.
How to fully understand the statements above?
The general rule for methods (static or otherwise) is to make them private if possible — i.e. unless you absolutely need them to be callable from other classes (which is to say, you need them to be part of your class’s public API)
The reason for making as much as possible private is simple: in the future, you’ll be able to change anything that is private, without breaking a bunch of other classes that were written to call the old version of the method. Changing a public method is more problematic, because other classes might be depending on it.
From http://sourcemaking.com/design_patterns/strategy/cpp/1:
class TestBed
{
public:
enum StrategyType
{
Dummy, Left, Right, Center
};
TestBed()
{
strategy_ = NULL;
}
void setStrategy(int type, int width);
void doIt();
private:
Strategy *strategy_;
};
Note how the private members have been declared at the end. I have seen this programming style at several other places, but somehow I find declaring private members first easier to read.
Are there any advantages of declaring private members at the end of the class, like done above?
When reading a class declaration the most important thing is the public interface and so it makes sense to go at the top. Your eyes shouldn't be drawn to the private members which hold the implementation.
It really doesn't matter much though. Pick a style (or be given one) and stick with it.
Actually, the only thing I can really think of it changing is the order of initialization of members. That seldom matters though.
Absolutely no, and I don't see why you should have benefits.
It's just a matter of personal taste, you should try to understand where your eyes prefer to look for them and stick that way.
In the original C++ implementation, all the members had to be declared at the beginning of a class, or code in the method definitions couldn't see them. The ability to define members at the end was added later, and some folks, relishing their new freedom, adopted this style and stuck with it. Either location makes sense, though.
Declaring private members at the end of a class is definitely a naming convention. Not required but easy to read since it's common to see them listed after public members.
However, you can also omit the "private:" part and just declare your private members outside of the public ones. If you do not put these variables under the "private:" part and just declare them outside (in this case, above) the "public:" area, they should automatically be defaulted to private.
I have a question about static member of class in c++, since the static member belongs to the class not any instance of class, so should the static member be declared as public, private?
Whether or not to declare a member public or private has nothing to do with whether it is static or not. You can have a static member be either public or private; both uses are acceptable depending on the situation.
Basically, if you want or need components outside of the class to have direct access to the static member, make it public. Otherwise, make it private.
Actually the static member is shared by all instances of the class. If it was a data member for example you could use is to count how many instances of the class were created. You can declare it either private or public or protected depending on your needs.
You're talking about making some static class members private to the class, so that instances of the class can't access them. Unfortunately I don't think c++ has any syntactical mechanism that you can use to enforce that at compile time. You might be able to pull off a runtime check, but it would be convoluted to say the least.
Really, I'm not sure why you would want to do what your asking. If you are already in ownership of and editing the class, you are also able to edit all the instance methods to ensure they don't use the static member. If you want to try to enforce it you'll have to put a big heavy comment next to your static member saying "Instance methods shouldn't use this" and make sure your team knows it. In general, you don't have to be religious about accessor modifiers like public/private in order to write good code so I would simply say don't worry about trying to enforce what you suggested.
Other object-oriented languages could provide what you are asking for as they draw more of distinction between classes and instances. e.g. Scala, Smalltalk.
I just want to make sure I got the idea of public and private right.
Regarding the private access specifier, does it mean:
Only accessed inside the class
Cannot be accessed from the object of the class unless there are public class methods that can be used to access them (Can other objects use those public functions?)
No other object can access them
And for public:
Accessed from the object of the class
Accessed from any other object
Is that right?
private : Only member functions and friends of class can access it.
public : Can be accessed anywhere where the object has scope.
Answering the questions -
private:
Yes
Yes. (Can other objects use those public functions? With out having class relations, one object of class cannot communicate to the other's members. )
Friends has access to private members of a class. So, answer depends upon your class has friends or not.
public:
Yes
Depends whether the object has hierarchical relations to the member's class you are trying to access.
I think there is an issue of vocabulary to begin with.
In C++ (and most languages) a class is a type. You can think about it as a blueprint to actually build something.
it describes the attributes that are held
it describes the methods to operate on those attributes
it describes the restrictions that apply: this is the "accessibility"
An object is produced by actually instantiating a class, that is, building what the blueprint described. It is more or a less a bundle of attributes. You can have several objects of the same class as you can have several houses from the same blueprint: note that their physical location is different for obvious reasons :)
Now, on to the accessibility. There are 3 typical levels of accessibility: public, protected and private.
public, as expected, means that everyone is given access to either attributes or methods
protected is somewhat less trivial. It means that only the object, or its children, may access the attributes (bad idea*) or methods. (Plus, in C++, friends)
private means that only the objects of that class (and not their children) may access the attributes or methods (Plus, in C++, friends)
Note: whatever the level of accessibility, an object has unrestricted access to all the attributes and methods of any object of the same class.
(*) Even though it pops up now and there, it is generally a bad idea to use protected attributes. The point of encapsulation is to hide the details, not only for the sake of it, but because by precisely controlling who can access the data, we can ensure that the class maintains its invariants (simple example, an array where you would store the size separately, you need to ensure that the "size" really represents the number of items in the array, at all times). Note: this restriction does not apply when you can seal a hierarchy, like in C# for example.
Private members can only be accessed by member functions and static functions of the same class and by friends of the class. It does not matter on which object that function is called. So the case
class Foo
{
private:
void bar() {}
public:
void baz(Foo& var)
{
var.bar();
}
}
is perfectly legal.
That seems correct. Data members and functions marked public can be accessed from anywhere by anyone. Data members and functions marked private can only be accessed by the class and its friends. However, a member function of a class can access data with any access specifier, so a public function can read and write private data members (this is used universally in OOP).
In c++ data and fn are encapsulated as 1 unit.
We begin a program by writing
preprocessor directives
Then, class declaration
Followed by function(fn) declaration where we also specify the access modifier ( public, private or protected)
& finally the main () program.
If we declare a fn
Private:the data within an object of a class is only accessed by fn defined within it- (the object which has the data and the private fn)
Public:the data can be accessed by any fn
Protected:similar to private however data can also be accessed by sub-classes that inherit the properties of another class.
Example if class A inherits from class B, thenA is a subclass of B.
Is there any way I can access Private member variable of a class?
Editing:
Not from a member function or friend function but through an instance.
GotW #76 has fascinating language-lawyery details on how to do some of this stuff. :-)
Just cast it around, shift memory and cast back. (didn't compile the code, but you should get the idea).
class Bla
{
public:
Bla() : x(15), str("bla") {}
private:
int x;
std::string str;
}
int main()
{
Bla bla;
int x = *((int*)(&bla));
std::string str = *((std::string*)((int*)(&bla) + 1));
std::cout << x << str;
return 0;
}
Since this is an interview question, I won't go into why you shouldn't do that. :)
EDIT:
Classes with virtual functions will have virtual table pointer somewhere there as well. I'm not sure if & will give you address of vt or address of first data member.
Alignment is 4 by default (right?), so if member you are reading does not align, shift by 2 bytes to get to the next one.
One of the "dirty tricks" of C++ is to do something like:
#define private public
#include "ClassHeader.h"
// now all the private members of the included class are public
I strongly do not recommend that you do this.
You could:
Place the private members in the public section
Make your class or function a friend of the class.
Provide an accessor to the data.
Take the address of the class, add the offset to that variable, cast, and dereference. (Yuck)
What are you trying to do? If something is private, don't mess with it. It's private for a reason.
Yes. You can access a private member:
...within other instances of the same (exact) type.
...within classes or functions declared to be a friend of that class.
...via a public accessor (getter/setter) member function.
While we're proposing bad ideas, there is nothing on the code end which enforces encapsulation -- it's entirely a compiler trick -- so you can write assembly to directly access private members.
But why not just rewrite the base class if it isn't doing what you want already?
Why would you want to?
Visibility rules are clear:
private methods are to be accessed only by methods of the class
protected methods can be accessed by methods of the class or descendants
public methods can be accessed by anyone
... hence -- if you're writing the class yourself, choose the right visibility. If it's a supplied class, thing carefully why it was made private in the first place...
If you decide to break that rule however, you have several options:
you can befriend the class that ought to access the private methods via a friend specifier
you can use an ugly preprocessor hack that probably someone posted already, but do it only if you need to use the fields or methods to do unit-testing -- any other use is bad design
you can use an ugly type-casting hack, but it's so ugly that I'm afraid to even post it not to get downvoted ;>
Yes why not , through a member function
I think it depends on how the question is phrased:
Q: How would you access a private member variable?
A: I wouldn't.
Along with:
Q: How would you implement ...
A: I wouldn't, it's already been done, I'd leverage an existing framework/library.
Interviewers don't always want to know if you can make a wheel, sometimes they are probing to see if you know how to find the nearest service station. :)