problem with constructors

Hello! I am new in c++ and i want some help. I want to learn how to make a constructor with object arguments. I give my source code and I want to tell me if I am right or wrong and why. Here's the code:

#include <iostream>
#include <string>

using namespace std;

class mydate
{
private:
string day,time;
public:
mydate(string a = "NO DAY",string b = "NO TIME")
{
day = a;
time = b;}

void printday()
{
cout << "\nDAY: " << day << "\nTIME: " << time;
}

};



class ap
{
private:
mydate date;
string desc;

public:
ap(string a = "NO DESCRIPTION",mydate o) //Theres my problem
{
desc = a;
date = o;
}


void printa()
{
cout << "APPOINTMENT INFORMATION:\n******************\n";
cout << "DESCRIPTION: " << desc;
date.printday();
}
};




main()
{
mydate d1("monday","14:45");
ap a1("mr.gordon_dentist");

a1.printa();

system("pause>null");
}
Your main needs to return an int.

You also need to define an operator = for mydate...

See below post for actual reason why it doesn't work...
Last edited on
You can only supply default arguments to the end of a function's parameter list.

1
2
3
4
5
6
7
8
9
//example, as to why this is...

void f(int x, int y = 0); //fine
void f(int x = 0, int y); //nope, but why?

int main() {
  f(5); //Whoops! Which one whould it call? Is x = 5 and y = 0, or is y = 5 and  x = 0
  ...
}


I know this doesn't apply when the data types are different*, but it's the rule.

* one can not be implicitly cast to the other
^Oh wow...I can't believe I didn't see that...
I was working on my code and i thought this and it works but i dont know if it is general take a look:
#include <iostream>
#include <string>

using namespace std;

class mydate
{
private:
string day,time;
public:
mydate(string a = "NO DAY",string b = "NO TIME")
{
day = a;
time = b;}

void printday()
{
cout << "\nDAY: " << day << "\nTIME: " << time;
}

};



class ap
{
private:
mydate date;
string desc;

public:
ap(string a = "NO DESCRIPTION",mydate o = mydate()) //Here's my solution
{
desc = a;
date = o;
}


void printa()
{
cout << "APPOINTMENT INFORMATION:\n******************\n";
cout << "DESCRIPTION: " << desc;
date.printday();
}
};




main()
{
mydate d1("monday","14:45");
ap a1("mr.gordon_dentist");

a1.printa();

system("pause>null");
}
Your main still isn't returning an int.

Anyway, yeah that will work. However, as it stands, someone can do this:

ap some_ap = "some_desc";

You might want to make the constructor explicit if you didn't intend for that.
Topic archived. No new replies allowed.