Wenliang Shao
Wenliang Shao

Reputation: 38

Why const function can use a static member object's non-const function?

Code1:

#include <iostream>
using namespace std;

class Test1 {
public:
  Test1() { num_ = 10; }
  int GetNum() { return num_; }

private:
  int num_;
};

class Test2 {
public:
  int GetNum() const { return t1_.GetNum(); }

private:
  static Test1 t1_;
};

Test1 Test2::t1_;

int main(int argc, char *argv[]) {
  Test2 t2;
  cout << t2.GetNum() << endl;
}

Code2:

#include <iostream>
using namespace std;

class Test1 {
public:
  Test1() { num_ = 10; }
  int GetNum() { return num_; }

private:
  int num_;
};

class Test2 {
public:
  int GetNum() const { return t1_.GetNum(); }

private:
  Test1 t1_;
};

int main(int argc, char *argv[]) {
  Test2 t2;
  cout << t2.GetNum() << endl;
}

The difference between two code is that code1's t1_ is static. And Code1 works. But Code2 raise a error:

error: passing ‘const Test1’ as ‘this’ argument of ‘int Test1::GetNum()’ discards qualifiers [-fpermissive] int GetNum() const { return t1_.GetNum(); }

Why Code1 can work?

Upvotes: 1

Views: 30

Answers (1)

songyuanyao
songyuanyao

Reputation: 172924

As non-static data member, t1_ becomes const accordingly in const member function. Then t1_.GetNum() leads to the error because non-const member function can't be called on const object.

On the other hand, static data member doesn't belong to object; it won't become const just because in const member function.

Upvotes: 2

Related Questions