Is it necessary to declare the private section of a C++ class?

J

James Kanze

Moreover: Declare *the public interface* of your module in the
header, put everything else in the compilation unit.

The whole point of the question, I think, is that C++ doesn't
allow this. You can't reopen a class in the compilation unit in
order to add private members.
 
J

Juha Nieminen

James said:
The whole point of the question, I think, is that C++ doesn't
allow this. You can't reopen a class in the compilation unit in
order to add private members.

Well, I said "whenever possible and feasible". For technical reasons
private member variables cannot be moved to the compilation unit, but
there are many other situations where it is possible to do so.

For example, rather than doing this:

// MyClass.hh
class MyClass
{
private:
class InnerClass
{
// large declaration here
};

InnerClass* innerClassPtr;
};

you can instead do this:

// MyClass.hh
class MyClass
{
private:
class InnerClass;
InnerClass* innerClassPtr;
};

// MyClass.cc
class MyClass::InnerClass
{
// large declaration here
};

(Naturally the above is possible only if 'innerClassPtr' is a pointer
or reference. If it's a member object, then that technique cannot be
used, for technical reasons.)

Likewise the nameless namespace should be used as much as possible and
feasible, rather than putting everything in the header file.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,780
Messages
2,569,608
Members
45,251
Latest member
41Ki

Latest Threads

Top