I wrote this simple const class method:
void CTest::MSGTest() const
{
MessageBox(_T("This is a simple test"));
}
This method has an error:
The object has type qualifiers that are not compatible with the member function CTest::MessageBoxW
I know this is because i use the const. A method can be a const method if no member variables are modify while the execution. I would like to know which variables the MessageBox modify and how the modification manifests.
I think it is the handler m_hWnd, but I don't know.
The problem isn't that neither your function nor MessageBox modify any members variables - they don't and that's easy to see.
The problem is that MessageBox is not marked as const and so you have a const member function (yours) calling non const one (MessageBox). This isn't allowed and that's the issue.
So why isn't it marked const? I doubt you will ever get a definitive answer to that question if one reason really exists.
Personally, I suspect it's a combination of factors that caused it to not be const originally and now it is what it is.
One potential reason is that a lot of internal MFC bits and pieces involve the manipulation and adjustment of maps - for example maps which associate windows HWND objects to MFC CWnd objects.
It's possible that they had to relax the use of const to account for calls to non const functions deep down the call chain in places that users never see.
So why not use mutable then or maybe even const_cast? Remember that MFC has been around for a long time and when it was designed the Microsoft compiler might not have support for some of the more exotic features of C++ at the time.
In my opinion, if CTest is derived from CWnd (explicitly or not) - showing a dialog box on this CWnd object means changing the state of window/control. Assume CTest is derived from a CDialog, and pressing some button causes this function (CTest::MsgTest) to be called. It effectively means that state of the dialog-box has changed (from user's perspective). It is not important if modal or modeless dialog is shown - the state has changed, hence the method shouldn't be const.
Related
I found multiple questions regarding custom QEvents. So since Qt 4 we have to derive from QEvent and register our custom type. There are some samples around.
What I want is a QWheelEvent with custom data in it. So the event should be usable everywhere as a "normal" QWheelEvent but if I want to I can check for my CustomWheelEvent type and retrieve the data from it.
The problem is that I don't know how to register the type because the constructor of the QWheelEvent does not offer the possibility to set the event type.
Looking at the internals of QEvent I could simply set the protected member Type t to an event type returned by registerEventType(). Does this have side-effects?
If I simply derive from QWheelEvent I can also use dynamic_cast to find out if it is my own event carrying my custom data. A simple static cast after a check for the type should be better though.
Any thoughts on this?
Edit: I have tried the approach with dynamic_casts but the cast seems to fail. This is possible if Qt deep-copies the event internally, so that a new QWheelEvent is created and passed through the event system instead of my CustomWheelEvent. This way my own data (defined in CustomWheelEvent) is stripped off the object and only the base class (QWheelEvent) is handled. I originally thought that the pointer is used as it is, so that I can rely on the dynamic_cast. More information on this is appreciated!
Read this:
Qt: Defining a custom event type
I think that you do want to register the event and that it will return a new unused type (number). In an example there, the static object sets the value to QEvent::None. The primary problem I see with the solution there is that it is not thread safe, so, be sure to make this thread safe somehow (like maybe call the static type method before things start so that they are initialized before it could be used in a multi-threaded way).
I am trying to color the button by using CColorbutton class function setcolor. It is working fine when I have declared the member variable of button but it is not working when I directly get the handle by GetDlgItem(IDC_BUTTON1). Can anyone tell me the solution of this?
CColorButton* pWnd = (CColorButton*)GetDlgItem(id+i);
pWnd->SetColor(RGB(0,0,0),RGB(200, 153, 204));
First of all: Without declaring a variable for the button control you will not get it to run!
Why? A window Variable and using DDX-Control or using CWNd::SubclassWindow is the way, subclassing works in the MFC. Without subclassing the messages are not handled by the code that is used in CCOlorButton.
Yes you can use GetDlgItem and my do a hard cast to CColorButton, but this is extremely dangerous! Why? The window object you get is just a temporary CWnd object with no additional member variables. If you call a specific member function of a CColorButton, that uses additional data members you may destroy your memory/heap/stack content.
With a MFC control class you always need the specific object somewhere in memory to suavely cast a pointer that GetDlgItem returns!
If you have a member function you don't need a cast. If (for any other reason) you need to cast a CWnd pointer, it is wise to use STATIC_DOWNCAST/DYNAMIC_DOWNCAST to get ASSERTs when something is wrong.
If you do not declare and properly initialize a CColorButton variable then there is no CColorButton object in your program. So you are calling something that does not exist. You asked for the solution of this, but you already know the solution!
Related to: C++ private pointer "leaking"?
According to Effective C++ (Item 28), "avoid returning handles (references, pointers, or iterators) to object internals. It increases encapsulation, helps const member functions act const, and minimizes the creation of dangling handles."
Returning objects by value is the only way I can think of to avoid returning handles. This to me suggests I should return private object internals by value as much as possible.
However, to return object by value, this requires the copy constructor which goes against the Google C++ Style Guide of "DISALLOW_COPY_AND_ASSIGN" operators.
As a C++ newbie, unless I am missing something, I find these two suggestions to conflict each other.
So my questions are: is there no silver bullet which allows efficient reference returns to object internals that aren't susceptible to dangling pointers? Is the const reference return as good as it gets? In addition, should I not be using pointers for private object fields that often? What is a general rule of thumb for choosing when to store private instance fields of objects as by value or by pointer?
(Edit) For clarification, Meyers' example dangling pointer code:
class Rectangle {
public:
const Point& upperLeft() const { return pData->ulhc; }
const Point& lowerRight() const { return pData->lrhc; }
...
};
class GUIObject { ... };
const Rectangle boundingBox(const GUIObject& obj);
If the client creates a function with code such as:
GUIObject *pgo; // point to some GUIObject
const Point *pUpperLeft = &(boundingBox(*pgo).upperLeft());
"The call to boundingBox will return a new, temporary Rectangle object [(called temp from here.)] upperLeft will then be called on temp, and that call will return a reference to an internal part of temp, in particular, to one of the Points making it up...at the end of the statement, boundingBox's return value temp will be destroyed, and that will indirectly lead to the destruction of temp's Points. That, in turn, will leave pUpperLeft pointing to an object that no longer exists." Meyers, Effective C++ (Item 28)
I think he is suggesting to return Point by value instead to avoid this:
const Point upperLeft() const { return pData->ulhc; }
The Google C++ style guide is, shall we say, somewhat "special" and has led to much discussion on various C++ newsgroups. Let's leave it at that.
Under normal circumstances I would suggest that following the guidelines in Effective C++ is generally considered to be a good thing; in your specific case, returning an object instead of any sort of reference to an internal object is usually the right thing to do. Most compilers are pretty good at handling large return values (Google for Return Value Optimization, pretty much every compiler does it).
If measurements with a profiler suggest that returning a value is becoming a bottleneck, then I would look at alternative methods.
First, let's look at this statement in context:
According to Effective C++ (Item 28),
"avoid returning handles (references,
pointers, or iterators) to object
internals. It increases encapsulation,
helps const member functions act
const, and minimizes the creation of
dangling handles."
This is basically talking about a class's ability to maintain invariants (properties that remain unchanged, roughly speaking).
Let's say you have a button widget wrapper, Button, which stores an OS-specific window handle to the button. If the client using the class had access to the internal handle, they could tamper with it using OS-specific calls like destroying the button, making it invisible, etc. Basically by returning this handle, your Button class sacrifices any control it originally had over the button handle.
You want to avoid these situations in such a Button class by providing everything you can do with the button as methods in this Button class. Then you don't need to ever return a handle to the OS-specific button handle.
Unfortunately, this doesn't always work in practice. Sometimes you have to return the handle or pointer or some other internal by reference for various reasons. Let's take boost::scoped_ptr, for instance. It is a smart pointer designed to manage memory through the internal pointer it stores. It has a get() method which returns this internal pointer. Unfortunately, that allows clients to do things like:
delete my_scoped_ptr.get(); // wrong
Nevertheless, this compromise was required because there are many cases where we are working with C/C++ APIs that require regular pointers to be passed in. Compromises are often necessary to satisfy libraries which don't accept your particular class but does accept one of its internals.
In your case, try to think if your class can avoid returning internals this way by instead providing functions to do everything one would want to do with the internal through your public interface. If not, then you've done all you can do; you'll have to return a pointer/reference to it but it would be a good habit to document it as a special case. You should also consider using friends if you know which places need to gain access to the class's internals in advance; this way you can keep such accessor methods private and inaccessible to everyone else.
Returning objects by value is the only
way I can think of to avoid returning
handles. This to me suggests I should
return private object internals by
value as much as possible.
No, if you can return a copy, then you can equally return by const reference. The clients cannot (under normal circumstances) tamper with such internals.
It really depends on the situation. If you plan to see changes in the calling method you want to pass by reference. Remember that passing by value is a pretty heavy operation. It requires a call to the copy constructor which in essence has to allocate and store enough memory to fit size of your object.
One thing you can do is fake pass by value. What that means is pass the actual parameter by value to a method that accepts const your object. This of course means the caller does not care to see changes to your object.
Try to limit pass by value if you can unless you have to.
A while ago I read the Debugging Windows Programs book, and one of the tricks that it talked about extensively was calling functions from the Visual C++ debugger (quick)watch window.
As luck would have it, I don't have a copy on hand and the little documentation that I could find about this is really really poor.
So how DO you call a member function in the watch window? What if the function lives in a DLL? What if it is part of a namespace? Can you pass non-trivial parameters?
Let's use this example: I want to call the size() method of QList<MyType>, where MyType is a custom type.
Thanks!
It works and is hugely useful. You can evaluate expressions in the watch window or open the quick watch window (ctrl-alt-Q -- a very handy shortcut to know). It will let you call most forms of member functions. The only times it commonly tends to fail is if you've got overloaded operators, eg with smart pointers. For a simple class without overloaded operators you should find it should work well. I think it should accept non-trivial parameters (though obviously it depends how non-trivial!) As well as calling functions that return values, you can also call functions that modify the object -- there's no constraint on only calling getter methods.
The other kind-of-obvious thing to remember is that all variables are evaluated in the local stack frame, so ensure the variable is visible from the current point in the stack.
I'd say just write list.size() in the watch window, where list is an instance of your QList, but I'm not sure this works for all classes
Are you sure that you can call methods of objects while debugging code in Visual Studio? Because I was never able to do so. The closest debugging features I know is to have a quick watch on objects (including local objects in the stack, navigating through the call stack), or compile and continue (I used it in VC6) allowing to change the code, recompile and continue debuging from the last statement...
I need suggestions on how to solve the type of problems described below. I'm fairly new at C++ and OO-design.
I've learnt:
Pointers shall be avoided when ever they can be replaced by references.
Objects shall have no knowledge of objects that they don't need to know about.
But when creating objects having references to other objects we must pass these references as input arguments to the constructor. Thus we need to know about objects we should not not know anything about.
But look at the following example:
Suppose I have a object "Menu" that needs to have it's own timer object "Timer". I'd like to implement this association as a reference.
The object MenuHandler aggregates a lot of Menu objects but shall not have any knowledge about Timer objects. But when the MenuHandler creates a Menu object it must pass a Timer reference argument to the constructor. Thus, ****MenuHandler** must know about **Timer****.
Any suggestions on how to treat these kind of problems?
I'd hesitate to bless your choice of words when it comes to the two numbered points. They're a sign you're on the right way learning C++, but they might be misleading to other novices. When I take a look at your concrete examples, this becomes more obvious.
A MenuHandler should not create menus. The content of menus is determined by by the application, so the application object (or the Controller part, if you've implemented Model-View-Controller) should create menus. The MenuHander merely takes ownership of menus created elsewhere.
Also, it may make sense to give each menu its own timer. That means the relation can be described as "Has a"; the menu has a timer. The relationship usually implmented by references can be described as "Knows a" (the inheritance relationship is usally called "Is a"). If each Menu object has a Timer, it can be a member, and initialized by the Menu constructor(s). The Timer object internally may obtain a reference to the system clock in its constructor, but that's not your concern.
Why not simply make the Timer object a member (by value) of the Menu class?
I find that I produce better (more maintainable, faster, etc) code and that I'm more productive using references in C++ than I would be solving the same problem with pointers... I think the traditional answer to your example would be to have a factory object that creates menus. In this way, the MenuHandler doesn't need to know about the Timer class.
The MenuHandler creates a Timer object, passes it into the Menu constructor, and forgets about it. That seems entirely reasonable.
If the MenuHandler unnecessarily kept a reference to the Timer, that would be against the advice point #2.
In a more general case where you need to provide a class to another class in order to do some kind of callback, you avoid mutual dependency (both know each other) by using an interface.
Class A derives from the interface. Class B accepts the interface as paramater in the constructor and calls the virtual function from that interface when needed.
Also check the observer design pattern.
For #1 Be very careful with the lifetime of your objects. References are no that suitable to handle dynamic graph of objets ( like your menu, menuhandler, timer, etc... ). What if you want to change the timer object later ?
It's not a good idea to have references as members in a class if the lifetime of referenced objects is not really known.
Avoiding pointer does not mean using references everywhere, you should have a look at smart pointers which will be more suitable for what you want to do.