Declaration of struct variables in other class when obtained by getters - c++

I am using Qt 4.5 so do C++. I have a class like this
class CClass1
{
private:
struct stModelDetails
{
QString name;
QString code;
..... // only variables and no functions over here
};
QList<stModelDetails> m_ModelDetailsList;
public:
QList<stModelDetails> getModelDetailsList();
...
};
In this I have functions that will populate the m_ModelDetailsList;
I have another class say CClassStructureUsage, where I will call the getModelDetailsList() function. Now my need is that I have to traverse the QList and obtain the name, code from each of the stModelDetails.
Now the problem is even the CClass1's header file is included it is not able to identify the type of stModelDetails in CClassStructureUsage. When I get the structure list by
QList<stModelDetails> ModelList = obj->getModelInformationList();
it says stModelDetails : undeclared identifier.
How I can able to fetch the values from the structure? Am I doing anything wrong over here?

Since struct stModelDetails is private, it is not visible from outside the class. You should declare it in the public section of your class instead:
class CClass1
{
private:
QList<stModelDetails> m_ModelDetailsList;
public:
struct stModelDetails
{
QString name;
QString code;
..... // only variables and no functions over here
};
QList<stModelDetails> getModelDetailsList();
...
};

You need to use the fully qualified name CClass1::stModelDetails. Now it will tell you it is private :)

You've already gotten a couple of suggestions for how to attack your problem directly. I, however, would recommend stepping back for a moment to consider what you're trying to accomplish here. First of all, you've said you only really want the name member of each stModelDetails item. Based on that, I'd start by changing the function to return only that:
QList<QString> GetModelDetailNames();
or, quite possibly:
QVector<QString> GetModelDetailNames();
The former has a couple of good points. First, it reduces the amount of data you need to copy. Second, it keeps client code from having to know more implementation details of CClass1. The latter retains those advantages, and adds a few of its own, primarily avoiding the overhead of a linked list in a situation where you haven't pointed to any reason you'd want to use a linked list (and such reasons are really fairly unusual).
The alternative to that is to figure out why outside code needs access to that much of CClass1's internal data, and whether it doesn't make sense for CClass1 to provide that service directly instead of outside code needing to access its data.

The problem is that you declared stModelDetails as a private class. Putting it in the public section should fix your problem.

There are two problems:
1. Already mentioned is that you need to move stModelDetails to the public section of your class.
2. Because it is nested, the proper name for it outside of the class is CClass1::stModelDetails.
If you really need access to it from the outside, you may want to consider whether it should be a member of CClass1 or if it should be a stand alone class or struct. I usually only use nested classes/structs when they are an implementation detail of my class.

Related

Determine if method or member can be protected or private

It is possible to check (for example by gcc) which methods or members can be moved to protected or private section?
Consider the following part of code:
class foo{
protected:
void foo_method_1(){};
int foo_member_var;
};
class bar : public foo{
void bar_method_1(){
foo_method_1();
}
};
If you want to determine which members and methods of the foo class can be private, you have to move all of them to the private section. So it will look like this:
class foo{
private:
void foo_method_1(){};
int foo_member_var;
};
...
Now it won't compile, here's the first error thrown by GCC:
prog.cpp:5:8: error: 'void foo::foo_method_1()' is private
void foo_method_1(){};
From that you know, that you have to move the foo_method_1 to the protected section. So it will look like this:
class foo{
private:
int foo_member_var;
protected:
void foo_method_1(){};
};
...
Now it will compile. You have to repeat this process for every single method and member in your class. For public section you can do it in the same way as described above.
You can't do this programmatically, no. And that's actually a good thing.
Sure, you could create a tool that integrated with a C++ parser, then — one-by-one — made certain members functions private and left any there that didn't cause an error in your program.
But, in order to do that, your entire program would need to be visible to that tool. Maybe if you have a simple project that's not a problem, but if you're writing a library that's literally impossible.
Even if you could do it, your resulting class design would be an absolute mess. Only a human programmer knows which parts of the API are designed for public consumption or not, and that's not always the same as which parts of the API are currently being consumed.
Stick to the manual approach, but don't just replicate the way the machine would do it, randomly guessing based on what compiles and what does not compile. Use your brain and your memory of what this class is supposed to do, to determine which functions should be public and which should not.
Ideally, try to get it right when you're first designing your class! You should be spending far more time designing your program than actually programming it, lest you very quickly end up with maintenance nightmares like this.
No. The compiler sees your code, not your design.

Class interface query

I've been wondering about a design that I've been using for quite some time for my game engine and games. Let's say we have an Object class
class Object
{
public:
const std::string& getName() { return m_name; }
private:
std::string m_name;
}
Then, I have a class called ObjectManager, which holds an instance of Object. Now, I've been wondering if I should keep that instance private in ObjectManager and duplicate code so that it could call getName(), or make Object public which defeats the concept of encapsulation. Which design do you guys think is better?
Thanks for any help!
If your class contains an object that is usable by others, expose it. Encapsulation is meant to hide variables needed to do something. Certain data members don't fall into this.
Example:
Person tom;
tom.getEyes().getColor();
tom.getMouth().eat(tomato);
tom.legs().walk();
Person could hide everything but it would be cumbersome:
tom.getEyesColor(); // accessor for every eye feature
tom.eat(tomato);
tom.walkAndEat(); // every possible combination of actions
Further example:
grid.row(3).col(5).setText("hello");
Here a column class could expose many methods without the grid class having to be touched. This is the beauty of object oriented programming.
If you named your class ObjectManager i get the feeling it is managing Object instances for others so you ought to expose it. The other idea to use inheritance is also valid:
class ObjectManager : public Object
{
};
If you want to restrict the interface to methods only then keep the object private and use an accessor method that returns a const reference (and non const if needed) to the private object.
Also, inheritance is a good option if applicable.
It depends on what you're doing. If I understand your question correctly, I'd personally lean more towards making the Object a private member of ObjectManager and adding a function to ObjectManager to act as a proxy for Object::getName(). (Is this your question?) However if you're just wrapping particularly thinly and are not trying to do something particularly technical or what have you, I might be tempted to answer otherwise. It depends, but more than likely, go ahead and make it private and add the extra function. Note that this answer is based on the assumption that you're going to make heavy use out of inheritance here.
It really depends on the situation (Sorry for the non-answer!). If you do want to support strong encapsulation, you would probably want ObjectManager to look something like this:
public class ObjectManager
{
private:
Object obj;
public:
string GetNameOfInnerObject();
}
As you can see I changed the method header to be descriptive with respect to ObjectManager. This type of method naming can come in handy to abstract an object's more complex interactions within itself away.
Edit: It might help if you tell us what ObjectManager is supposed to do. Does it have any methods that don't correspond directly to your inner object?

Instance-level encapsulation with C++

I have a two-part question. First, I understand that C++ provides only class-level data encapsulation, meaning that all objects of the same class have access to one another's private members. I understand the reason for this, but have found some links (i.e. http://www.programmerinterview.com/index.php/c-cplusplus/whats-the-difference-between-a-class-variable-and-an-instance-variable/) which appear to contradict this point, suggesting that I could do the following:
class testclass {
private:
// Below would be an instance-level variable, and new memory for it is set aside
// in each object I create of class testclass
int x;
// Below would be a class-level variable, memory is set aside only once no matter
// how many objects of the same class
static int y;
}
What I would like to do is actually make this work, i.e., I would like to define a variable in a class which is private in each instantiation (this is my second question). Since the code snippet above does not appear to achieve this, is there a work around I can use to create data that is private to individual objects? Thank you!
EDIT:
It's true that I'm still learning OO basics. I'll use the ubiquitous car example to show what I'm trying to do, which I'm sure must be a common thing to try. I'd welcome any suggestions for how to rethink it:
class car {
private:
int mileage;
public:
car(int); // Constructor
void odometer();
};
car::car(int m) {
mileage = m;
}
void car::odometer() {
return mileage;
}
int main(void) {
car ford(10000), honda(20000);
cout<<ford.odometer(); //Returns 20000, since honda constructor overwrites private variable 'mileage'
}
Is there any way to get the odometer() method to return the mileage of either the ford or honda, depending on what I want?
Priviledge (public, private, protected) only applies to names. Only during the time when a name is resolved will the compiler apply permissions. Once compiled, all such information is gone.
In your example above, all uses of the names x and y within a scope that resolves to THOSE variables will be private to your class. Only functions declared in your class, be they static or not, will be able to access those variables by name.
All bets are off however if you give out the variable to other objects that can then refer to the variable by other names which have other permissions.
I'm not sure what you're asking with reference to "in each instantiation". AFAIK, there is no native way to make a variable private such that only that instance can access it. In all cases, instances can access each other's private parts.
There's some ways you could get around this I suppose. First is to templatize your class and give each instance a different type. You could do this with an integer template parameter or something. This could make life annoying though as you try to work with these types as the same kind of thing. You'd have to virtualize and have an abstract base class or something.
Currently that's the only method I can think of. All others depend on calling entities playing nice.
Generally speaking it's rare that you'd want to protect members from other instances. The usual case of the same type being passed to the same type is during copy and assignment, where you basically need all knowledge about the source to correctly copy. My bet is that you need to rethink what you're trying to do, whatever that is.

Using Custom Struct inside of Class Definition

This is a relatively simple question, but the specifics are confusing me.
I have a basic struct as follows:
struct player {
string name;
int rating;
};
and a class 'team' which would make use of this struct. With this in mind, where is the correct placement of the 'player' struct- inside the public/private fields of the team or in a separate file? Also, would there be anything different that I'd need to do in order to create an instance of it? Thanks.
You have to ask yourself a question. Is the struct player meaningless unless in conjunction with class team? If so, it should probably be defined inside team; otherwise, it should be defined independently.
That is: if someone can conceivably want to use a player object that has not been directly retrieved from a team, you should make player an independent struct. Since we don't know the general structure or idea behind your program, we cannot give you a direct answer.
It depends on the how you use team/player struct. If you player is used by other part of the application, you should put player independent, that's the most cases do.
struct Player {
int rating;
std::string name;
};
class Team
{
private:
std::vector<Player> players_; // here you have a bunch of players
};
if your Player is totally internally used by Team and no one is using it, you can put it inside Team struct/class to narrow down its name scope.
class Team
{
private:
struct Player{
int rating;
std::string name;
};
private:
std::vector<Player> players_; // here you have a bunch of players
};
simply define the struct before the class.
that should do the trick...
I think a team is a collection of players, so it is convinient to use some container for managing the team.
A lot of efficient containers can be found in STL, it is up to you to choose one which suits you needs best.
Also to mention, in order to group staff related to the same task you can use namespace.
The key is whether it ia possible to use Player without using Team. If so, it should be a separate class, and not nested. In well designed conventional (OO) software, most nested classes are used exclusively inside the outer class, and are private. Or they are proxies, used for return values from functions of the outer class, but never declared by clients of the outer classes.
It may also be deemed advisable to make other "views" of the class member classes; e.g. iterators into a container. Whether iterators should be members, or free classes, is more of a style issue than anything else (but you should be consistent); it mainly affects the name (ContainerIterator vs. Container::Iterator).
Finally, templates introduce another dimension: given a template on a type T, it's easy, within this template, to reference members, including member types, of T; it's impossible to find "unrelated" types. In other words, if you instantiate the template with T == Container, Container::Iterator is readily available as typename T:Iterator, but you have no way of finding ContainerIterator.
Given the names of your classes, I suspect very strongly that they should be independent, with Team having a 1-n containment relationship to Player. (I also suspect that both are entity objects, and should be made uncopyable and unassignable. But that's another issue.)

Can there be two public section in a class? If yes then why ? And in which circumstances we do so?

There is something bugging me about classes. For example
class A
{
public:
A()
{
.....
.....
}
void cleanup()
{
....
....
....
}
public:
UINT a;
ULONG b;
};
In the above example there are two public section. In the first section I am defining a constructor and a method and in the second section I am declaring data members. Is the above class i.e. A correct. Can we do that? If yes then why is that needed and in what circumstances should we use it? Since we can do the entire thing in one section then why are there two sections?
Access qualifiers simply apply to the code that follows until the next qualifier. There is no restriction on the number or order of such qualifiers.
It is generally not necessary to repeat the same access qualifier in a class, and doing so is likely to confuse the reader. They also may have an effect on the layout of a class, since data members following the same qualifier must be laid out in the order they are declared, but there is no such restriction between qualifiers.
As Marcelo says, you can use the public, private and protected qualifiers as many times as you wish. "When" is entirely personal. Some people like this:
class AClass
{
public:
// all the public stuff
protected:
// all the protected stuff
private:
// all the private stuff
};
but personally (and this really is just a personal preference) I like to do this:
class AClass
{
// constructors and destructors
public:
// public cons/dest
protected:
// protected cons/dest
private:
// private cons/dest
// accessors
public:
protected:
private:
// methods
public:
protected:
private:
// members
public:
protected:
private:
};
Feel free to come up with your own style, whatever you're comfortable with. There is no right or wrong way of doing it. Just try to be consistent.
Yes its correct however personally I prefer to just have one public section at the top of the class, that's where programmers looks first when examining a new class. It is then easier to see which parts are supposed to be accessible and which are not -- instead of browsing the whole class header.
I usually try to arrange the declaration of the class so that it's easy for others to use the said class.
The usual is thus: public/protected/private, in this order, because it simplifies life for the readers.
People who use the class can stop reading once reaching the protected tag, anything after is none of their concern.
People who derive from the class can stop reading once reaching the private tag, anything after is implementation detail.
This, coupled with not writing the code of the methods at their point of declarations, makes for an easy to read interface.
There are however a couple of tricks:
when using metatemplate programming, you may need to declare types first, methods afterward, so you end up with 2 series of public/protected/private
when using the Key idiom (instead of friend), you have a public section that is in fact dedicated to only a small portion of the users and is best isolated either at the bottom of the normal public section or after the protected section.
Finally, as to comment about the layout issue among the attributes. Encapsulation means that attributes should be private. So, either you have a struct and everything is public or you have a class and everything is private, mixing the two means breaking encapsulation, and that's a bug in the making.
The class is correct, public is just a access qualifier and will apply till the next qualifier is seen or the end of class declaration. There is no limit to how many of these access qualifiers(public, private, protected) you can have in a class. As to why this is useful, it helps writing class declarations the way you want. For example I might want all the member functions (public,protected or private) declared before the (say) private data members.
As #Marcelo Cantos's answer explains, this is allowed. When writing code yourself you should avoid this, as it only leads to confusion when others read your code. The only place I have ever seen this in real life is in the code generated by various MFC-wizards. Whenever you add some thing to your class using a wizard, it would just add an extra section to the end of your class.