Sizeof static member object?

This is a discussion on Sizeof static member object? within the C++ Programming forums, part of the General Programming Boards category; Why can't I use sizeof on foo::i in a member function but I can use it in main()? Code: #include ...

  1. #1
    Registered User
    Join Date
    Jan 2008
    Posts
    65

    Sizeof static member object?

    Why can't I use sizeof on foo::i in a member function but I can use it in main()?
    Code:
    #include <iostream>
    
    class foo {
    public:
    	static int i[];
    
    	void bar()
    	{
    		int s = sizeof(i); //gives error C2070: 'int []': illegal sizeof operand
    	}
    };
    
    int foo::i[] = {1,2,3};
    
    int main()
    {
    	int s = sizeof(foo::i);
    }

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    You cannot take sizeof on an incomplete type. Until you initialize foo::i, it's length is unknown, hence its type is unknown. So the lookup in main works, since at that time foo::i is an int[3]; but the lookup in bar fails, since at that time foo::i is an int[]. ETA: You should be able to make it work if either (a) you move the definition of bar below the initialization of i, or (b) give i a size in its declaration.

  3. #3
    The larch
    Join Date
    May 2006
    Posts
    3,573
    Probably because at that point in the file, the sizeof i is indeed unknown.

    You may try moving the implementation of bar below the definition of i.
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. seg fault at vectornew
    By tytelizgal in forum C Programming
    Replies: 2
    Last Post: 10-25-2008, 02:22 PM
  2. uploading file to http server via multipart form data
    By Dynamo in forum C++ Programming
    Replies: 1
    Last Post: 09-03-2008, 05:36 AM
  3. const correctness and static member variables
    By cunnus88 in forum C++ Programming
    Replies: 2
    Last Post: 02-21-2008, 05:26 PM
  4. Static member functions more efficient?
    By drrngrvy in forum C++ Programming
    Replies: 6
    Last Post: 06-16-2006, 08:07 AM
  5. filling a static member map variable
    By elad in forum C++ Programming
    Replies: 2
    Last Post: 09-17-2004, 01:43 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21