default constructor

Hi all,

How do you write a default constructor? I'm struggling with it :(

I need to use a default constructor that will initialize the data members:
- salesPerson to “Unknown”
- noOfWeek to 13
- amount to point to an array of thirteen 0.00s.

This is my weeklysales class

1
2
3
4
5
class WeeklySales {
char* salesPerson;
double* amount; // Pointer to an array
int noOfWeek; // Size of the array
};



Here's my attempted code:

1
2
3
4
5
6
7
   //default constructor
   WeeklySales (){
	   
	   salesPerson="Unknown";
	   noOfWeek = 13;
	   amount = 0.00;
   }


Anyone can help me out?
Thanks for any help you can give me :)
Last edited on
Note that amount is a pointer, so you will need to give it the address of a double, possibly via dynamic allocation. If salesPerson is ever intended to be changed, you'll want to do the same for it.
Hi thanks for the reply. I am quite new to C++. Therefore I am struggling with writing the codes. How do you write the code to initialize it?
Your code would be fine for non-pointer variables, so you problems have nothing to do with the concept of writing a constructor itself (expect perhaps you'll want to use an initializer list). Look up how to use pointers, as that's where you're problem lies.

Edit: This tutorial has some information I think will be useful:
http://www.cplusplus.com/doc/tutorial/dynamic/
Last edited on
Yeah what Zhuge is saying basically is that since amount is a pointer, you either need to have it point at a double or dynamically allocate one.

To dynamically allocate it

1
2
3
4
5
6
//default constructor
   WeeklySales (){
	   amount = new double(0.00);
	   salesPerson="Unknown";
	   noOfWeek = 13;
   }


I strongly suggest you read this before you start dynamically allocating things however : http://www.cplusplus.com/doc/tutorial/dynamic/
Last edited on
I tried doing it and i got this:

1
2
3
4
5
6
  WeeklySales (){
	   
	   salesPerson="Unknown";
	   noOfWeek = 13;
	   amount = new double [0.00];
   }


but there is a red curly underline error message underneath [0.00] which says "expression must have integral or enum type".
you can't create an array like this. Do it like so:
1
2
3
	   amount = new double [13];
	   for(int i = 0; i < 13; i++)
	     amount[i] = 0.00;
but there is a red curly underline error message underneath [0.00] which says "expression must have integral or enum type".

Well, yes. What sense would it make to have a non-integral number for your array size? How could you possibly have, say, 3.57 elements in an array? Of course the size of the array has to be an integer!
oh i see! sorry for my dumbness.... :(
thank you so much for the help!
No need to apologize - there's a lot to take in when you're learning C++ :) You're welcome!
Topic archived. No new replies allowed.