copy/Constructor and destructor help!

Hi,

My teacher gave us this problem for homework after horribly explaining the process. Can someone help with the main program? I have an idea of what it should probably look like....


This was the homework problem:

In a separate C++ implementation file, implement each of the 5 functions defined. The default ctor should set the data values to 0.0.

class Complex
{
public:
Complex(void); /* Default ctor */
Complex(const double r, const double i); /* Preferred ctor */
Complex(const Complex& src); /* Copy ctor */
virtual ~Complex(void); /* dtor */
Complex& operator= (const Complex& src); /* Assignment operator */
protected:
double real;
double imag;
};





I believe the result should look something like this (?)

#include<iostream>
#include “Complex.h”
Using namestring std;
Int main()
Complex(void)
{
real = 0.0;
imag = 0.0;

}
Complex(const double r, const double i);
{
real = r;
imag = i;

}

virtual~Complex(void);
{
real = 0.0;
imag = 0.0;
}

Complex& operator= (const Complex& src);
{
real = 0.0;
imag = 0.0;
}

Return 0;
}

It looks almost right. When you define functions (including constructor, destructors and operators) outside the class you need to specify which class the function belongs to by placing the class name followed by :: before the function name.
1
2
3
4
5
Complex::Complex(const double r, const double i);
{
	real = r;
	imag = i;
}


You should also not use the virtual keyword when defining the destructor.
Thanks for responding!

I tried what you said but it is still giving me an error saying under the destructor and assignment operator that real and imag are "undefined".

Also '(void)' for the default constructor is "error: type name is not allowed"

Also also 'operator' is "not a member function" what the heck?!

WTF you can't define your class's functions inside your main function...
Last edited on
Huh?
The correct way is:
1
2
3
4
5
6
7
8
9
10
11
12
//Complex.h
class Complex
{
public:
    Complex(void); /* Default ctor */
    Complex(const double r, const double i); /* Preferred ctor */
    Complex(const Complex& src); /* Copy ctor */
    ~Complex(void); /* dtor */
    Complex& operator= (const Complex& src); /* Assignment operator */
protected:
    double real, imag;
};


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
//Complex.cpp
#include “Complex.h”

Complex::Complex(void) : real(0.0), imag(0.0)
{

}
Complex::Complex(const double r, const double i) : real(r), imag(i)
{

}

Complex::~Complex(void);
{
    // Do not make sense set variables you are destroying
    //real = 0.0;
    //imag = 0.0;
}

Complex& Complex::operator=(const Complex& src);
{
    this->real = src.real;
    this->imag = src.imag;
    
    return *this;
}

Last edited on
Topic archived. No new replies allowed.