Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing a variable in a union which is inside a class

Tags:

c++

class

Sorry for naive question in C++. For below code, there is a class, inside which there is a union declaration having two variables. How to access the variables in the union using the class object in code below:

class my
{

public:
//class member functions, and oeprator overloaded functions

 public:

    union uif
    {
    unsigned int    i;
    float       f;
    };

private:
//some class specific variables.

};

if there is an object of type my defined like

my v1;

in a function later

Using v1 how do i access float f; inside union above in code?

also I want to watch the value of this float f in the watch window of a debugger(VS-2010), how to do that?

I tried v1.uif.f , this gave error in the watch window as : Error oeprator needs class struct or union.

v1.

like image 998
goldenmean Avatar asked Dec 16 '22 09:12

goldenmean


1 Answers

You are only defining the union within the scope of the class, not actually creating a member variable of its type. So, change your code to:

class my 
{ 

public: 
//class member functions, and oeprator (sic) overloaded functions 

 public: 

    union uif 
    { 
    unsigned int    i; 
    float       f; 
    } value; 

private: 
//some class specific variables. 

}; 

Now you can set the member variables in your union member, as follows:

my m;

m.value.i=57;
// ...
m.value.f=123.45f;
like image 179
Michael Goldshteyn Avatar answered Dec 31 '22 01:12

Michael Goldshteyn