Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sizeof(*this) in class definition

Tags:

c++

Can we do something like this:

#include <iostream>

class Foo
{
public:
   Foo() { std::cout << sizeof(*this) << '\n'; }
};

In C Standard i see the following:

ISO/IEC 9899:2011

6.7.2.1 Structure and union specifiers

8 ... The type is incomplete until immediately after the } that terminates the list, and complete thereafter.

But in C++ Standard i can't find any analogue.

The sizeof operator shall not be applied to an expression that has incomplete type, so can we write such code or not?

like image 713
FrozenHeart Avatar asked Jan 23 '13 18:01

FrozenHeart


2 Answers

Yes, you can write such code because the compiler has to treat it as though the class definition is complete inside class method implementations.

For example it has to treat it as though you wrote:

#include <iostream>

class Foo
{
public:
   Foo();
};

// Methods declared in the body of a class are implicitly inline
// Inline, however, probably doesn't mean what you think it means:
inline Foo::Foo() { std::cout << sizeof(*this) << '\n'; }
like image 189
Mark B Avatar answered Oct 16 '22 07:10

Mark B


Inside the member function body, the class is complete- else, you could not access any other member functions, nor access any member variables, which would make a fairly worthless member.

like image 30
Puppy Avatar answered Oct 16 '22 09:10

Puppy