Im having a little trouble with a program i am writing. I have a class heirarchy:
Project
--> SimpleProject
--> MinorProject
ect...
and another class:
Task
Now task has a pointer to a Project object in it's private section of the class definition.
Here is Task.h
Code:
#ifndef TASK_H
#define TASK_H
// forward declaration
class Project;
class Task
{
public:
Task();
Task(const Task & t);
Task(int, const Project &);
~Task();
void DoIt();
Task & operator=(const Task & other);
friend std::ostream & operator<<(std::ostream & os,
const Task & t);
friend bool operator==(const Task & left,
const Task & right);
friend bool operator!=(const Task & left,
const Task & right);
private:
int id;
Project *pp;
};
#endif
Now i want the Project *pp pointer to point to a derived class of Project (SimpleProject, MinorProject).
I defined the constructors of Task like this (Task.cpp):
Code:
/**
* Default Constructor
*/
Task::Task()
{
// do nothing
}
/**
* Constructor with id and reference to project.
*/
Task::Task(int in_id, const Project & in_pp)
{
*pp = in_pp; // is this wrong?
id = in_id;
}
/**
* Copy Constructor.
*/
Task::Task(const Task & orig)
{
id = orig.id;
pp = orig.pp;
}
Of so the id is getting set but for some reason the pp pointer is not being set. It is always the same memory address for each pp pointer even if i create more than on instance of the class. Do i have to dynamically create the Project that pp is pointing to in the constructors? But if i do that then i will have to know what type of project it is.
My main file is:
Code:
#include <iostream>
#include <iomanip>
using namespace std;
#include "Task.h"
#include "SimpleProject.h"
#include "MinorProject.h"
#include "MajorProject.h"
int main()
{
SimpleProject *sp1 = new SimpleProject();
SimpleProject *sp2 = new SimpleProject(*sp1);
SimpleProject *sp3 = new SimpleProject(*sp1);
Task *t1 = new Task(1, *sp1);
Task *t2 = new Task(2, *sp2);
Task *t3 = new Task(*t1);
sp1->AddTask(*t1);
sp2->AddTask(*t2);
sp3->AddTask(*t3);
cout << *sp1 << endl;
cout << *sp2 << endl;
cout << *sp3 << endl;
cout << (*sp1 == *sp2) << endl;
delete sp1;
delete sp2;
delete sp3;
return 0;
}
The only thing that is not working is the pp pointer in Task obejcts.
Can anyone help me out?