开发者

const correctness

I was going through: C++ FAQs about inheritance and decided to implement it (just to learn it)

#include "Shape.h"

 void Shape::print() 开发者_运维问答const
 {
     float a = this->area();  // area() is pure virtual
     ...
 } 

now, everything (well, almost) works as described in item: faq:23.1 except that print() is const and so it can't access the "this" pointer, as soon as you take out const, it works. Now, C++ FAQs have been around for a while and are usually pretty good. Is this a mistake? Do they have typo or am I wrong? If I'm wrong, I would like to know how is it possible to access the "this" pointer in a const function.


The problem is that the area() function is not const. If that function was const, then this would compile fine. Since your inside a const function, the this pointer is const and therefore you can only call const functions on it.


Why couldn't this be accessed? The point is, only const members and methods can be used. So if Shape::area() is declared const, there is no problem. Also, you can freely read data member values, but not assign to them:

class Shape 
{
  int i;
  void print() const;
  virtual float area() const = 0;
  virtual void modify() = 0;
};

void Shape::print() const
{
  float a = this->area(); // call to const member - fine
  int j = this->i;        // reading const member - fine

  this->modify();         // call to non const member - error
  this->i++;              // assigning to member - error
}


If print is defined as const, then it can use this to access const members but not to access non-const members: so it can invoke this->area() if-and-only-if the area method is declared as const (i.e. if the area method promises that if it's invoked then it won't mutate its Shape instance).


It is also a good practice to declare all functions as const by default, and only not do so when you actually need to modify the object. This will also help finding errors of the kind where some function modifies something it is not meant to.


You certainly can access the this pointer, but in a const function it becomes a pointer to a const object. Remember, the this pointer isn't a real pointer instance, so it can change its type at different points in the program.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜