jason
jason

Reputation: 7164

c++ Allocating memory for a class

I have this class :

class myClass{
    public:
        myClass(string label);
        ~myClass();
        string myget();
        void myset(string label);

        void myadd(class2 * edge);
    private:
        string label;
        vector<class2 *> myList;
};

I want to write a function which checks the equality of objects of type myClass :

 bool operator== (myClass& l,myClass& r)
{         

}

In order to check myList vectors of those objects, I wanted to copy l and r, sort the vectors of copies and the check if the sorted vectors of those copies are equal. But I think I failed making copies of l and r. Here is what I wrote for that :

myClass x = new myClass("s1");
myClass y = new myClass("s2");


x = l;
y = r;
sort(x.myList.begin(),x.myList.end());
sort(y.myList.begin(),y.myList.end())
if( x == y)
    return true;
    else
    return false;

This code gives this error : error: conversion from 'myClass*' to non-scalar type 'myClass' requested.

I tried making x and y pointers but it didn't work either. Can you tell me how I can fix this code?

Thanks in advance.

Upvotes: 1

Views: 127

Answers (3)

Mats Petersson
Mats Petersson

Reputation: 129524

Assuming you only need the class to "live" for the duration of your class, you can do:

  myClass x("s1");

Or

  myClass x = myClass("s1");

If you need to have a pointer to the class, so that this function can pass it back to a calling function:

  myClass *x = new myClass("s1");

Upvotes: 3

user2385009
user2385009

Reputation: 101

Are you forgetting to declare x and y as pointers?

myClass* x = new myClass("s1");
myClass* y = new myClass("s2");

Upvotes: 4

Andrew
Andrew

Reputation: 24866

myClass x = new myClass("s1"); - here is the problem

Operator new returns a pointer. So you either store a pointer or just create your copy on the automatic storage (usually referenced as stack)

myClass x = myClass("s1"); - should be so (stack)
myClass *x = new myClass("s1"); - or so (heap)

Upvotes: 5

Related Questions