Question

I've looked as best I can and can't find much on this particular topic. I have to take a large number of variables, maybe for more than one object and pass them through a set of functions so I think this is the best way to do it.

I'd like to pass a struct to a constructor for a class where the struct is not defined. Is this possible? My code looks something like this:

class myClass
{
protected:
   double someVar;
   .
   .
public:
   myClass(struct structName);  //compiler is ok with this
   myClass();                   //default construct
};

struct structName
{
   double someOtherVar;
   .
   .
};

myClass::myClass(??????)  ///I don't know what goes here
{ 
  someVar = structName.someOtherVar; ///this is what I want to do
} 

EDIT: Am I supposed to declare a struct in the class and use that struct as the parameter?

Was it helpful?

Solution

In fact you already wrote all. Only instead of struct structName I would use const struct structName &

myClass::myClass( const structName &s )
{ 
  someVar = s.someOtherVar; 
} 

Or you could define the constructor as

myClass::myClass( const structName &s ) : someVar( s.someOtherVar )
{ 
} 

In this declaration

   myClass(struct structName);  

struct structName is so-called elaborated type name. It introduces a new type in the namespace where the class is defined.

In your example you at first declared the structure and then defined it. The constructor declaration does not require that the structure would be a complete type.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top