operator overloading and return type is an object

i am trying to execute the following code, i keep on getting error, that: time does not name a type, for time time::operator+(const time &a) const

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
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
using namespace std;



class time {
    private:
        int m;
        int h;
    public:
        time(): m(0),h(0) {}
        time(int x,int y): m(x),h(y) {}
        int getm() const {return this->m;}
        int geth() const {return this->h;}
        void print() const;
        time operator+(const time &a) const; //typo was int
        time operator-(const time &a) const;


};

void time::print() const
{
    cout <<"Hour: "<<h<<endl<<"Mins: "<<m<<endl;
}

time time::operator+(const time &a) const
{
    time temp;
    temp.m= m+a.getm();
    temp.h=h+a.geth();
    return temp;

}





also
given i have a double pointer pointing to a pointer and that pointer pointing to a dynamic data.

1
2
3
4
int *ptr=new int
int **p=&ptr;

delete p;


so will delete p, first delete dynamic data, then the pointer ptr ?
Last edited on
In your class definition, operator+ returns an int, yet in your implementation, operator+ is returning a time.

so will delete p, first delete dynamic data, then the pointer ptr ?
p itself was not dynamically allocated. Don't delete p;. If anything you'd want to delete *p;.
Last edited on
sorry that was me testing it, if it would for int, i forgot to change it back.

the edited code above (correct decleration) it still tells me that time is not a name type.

Also, what if ptr was dynamically allocated, then would delete ptr, delete the dynamically created pointer or the data set
The code as shown looks OK. Is the code you're using perhaps not exactly as shown? The "does not name a type" error suggests that the compiler is seeing the implementation of operator+ but it doesn't know about the class time because its definition probably hasn't been #included. Ensure that the header file including the time class definition has been included. Also, be sure that you're not using <time.h> or <ctime> because that time might conflict with your time since you're using namespace std; with your time definition.

Also, what if ptr was dynamically allocated, then would delete ptr, delete the dynamically created pointer or the data set

If ptr points to an array of objects, then the destructors of the objects will be called and then the memory will be released. After that, don't try to access the memory pointed to by ptr because you will likely get a segmentation fault or read garbage. Does that answer your question? If not, consider showing a small example of what you mean so I can help better.
Topic archived. No new replies allowed.