I have two classes: Location and Adress. Adress contains a member named l1 which is of the type Location.
class Location
{
double lat, lon;
char *em;
public:
Location(int =0, int=0, const char* =NULL);
~Location();
Location (const Location&);
friend ostream& operator<< (ostream&, const Location &);
};
class Adress
{
char *des;
Location l1;
char *country;
public:
Adress(char *,Location &, char *);
virtual ~Adress();
friend ostream& operator<< (ostream&, const Adress &);
};
Adress constructor:
Adress::Adress(char *des, Location &l1, char *country)
{
if (des!=NULL)
{
this->des=new char [strlen (des)+1];
strcpy (this->des, des);
}
if (country!=NULL)
{
this->country=new char [strlen (country)+1];
strcpy (this->country, country);
}
}
Location constructor:
Location::Location(int lat, int long, const char *em)
{
this->lat=lat;
this->lon=lon;
if (emi!=NULL)
{
this->em=new char [strlen (em)+1];
strcpy (this->em, em);
}
}
What I want to do is when I call the constructor of the class Location in the main function for creating a new object to automatically call the constructor of the location class, something like: Address ("desc", l1 (43.23, 32.12, "south"), "country")
. I have tried in many ways but none of them seems to work. Sorry for my mistakes, I'm a begginer.
It seems you want to pass temporary location object to Address constructor so your parameterized constructor definition should be changed to accept const Location& and here is sample code for what you want to achieve :
class Location
{
double lat, lon;
char *em;
public:
Location(int =0, int=0, const char* =NULL);
~Location();
Location (const Location&);
friend ostream& operator<< (ostream&, const Location &);
protected:
private:
};
class Adress
{
char *des;
Location l1;
char *country;
public:
Adress(char *,const Location &, char *);
virtual ~Adress();
friend ostream& operator<< (ostream&, const Adress &);
protected:
private:
};
Adress::Adress(char *des, const Location &l1, char *country)
{
if (des!=NULL)
{
this->des=new char [strlen (des)+1];
strcpy (this->des, des);
}
if (country!=NULL)
{
this->country=new char [strlen (country)+1];
strcpy (this->country, country);
}
}
Location::Location(int lat, int lon, const char *em)
{
this->lat=lat;
this->lon=lon;
if (em!=NULL)
{
this->em=new char [strlen (em)+1];
strcpy (this->em, em);
}
}
int main()
{
Adress ("desc", Location (43.23, 32.12, "south"), "country");
return 0;
}
Also you cannot call class constructor with object name so l1 should be changed to class name i.e Location
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments