[solved]Calling a copy constructor using 'this'

I have my copy constructor defined like so:
1
2
3
4
5
6
CardStack::CardStack(const CardStack &pCS)
{
    foreach(Card c, pCS){
        this->append(c);
    }
}

From within the same class I would like to call the copy constructor to make a temporary CardStack instance:
1
2
3
4
5
6
7
void CardStack::initSortedArray()
{
    this->_sortedIndexes.clear();
    CardStack cs = new CardStack(this);   // error on this line
    std::sort(cs.at(0), cs.at(cs.count()), CardComparator());

}

I get an error 'no matching function call' on the call to the copy constructor:

/home/noone/TestQt/cardstack.cpp:23: error: no matching function for call to ‘CardStack::CardStack(CardStack*)’
23 | CardStack cs = new CardStack(this);
| ^

How do I pass the current instance to the copy constructor?
Last edited on
this is a pointer, not a reference. So you can try CardStack(*this); instead, I suppose. Strange design, probably avoidable.

Also, you shouldn't need to dynamically allocate anything on line 4. Just do CardStack cs(*this); But I see you're using some weird non-standard syntax (like your foreach loop), so maybe what you have is correct.
That worked:
1
2
3
4
5
6
7
void CardStack::initSortedArray()
{
    this->_sortedIndexes.clear();
    CardStack cs(*this);
    std::sort(cs.at(0), cs.at(cs.count()), CardComparator());

}

The foreach is a macro (?) and comes from QT.
I would image everything is "weird non-standard" with my code as I try to learn c++ and QT simultaneously.
lol.

Thank you for the help.
Ah, yes the 'foreach' thing is a Qt macro. Qt documentation says that you should prefer C++11 for-each loops instead ("range-based for loops").
https://www.learncpp.com/cpp-tutorial/for-each-loops/
Thanks for the tip. (That syntax is the same as Java)
I changed it as recommended:
1
2
3
4
5
6
CardStack::CardStack(const CardStack &pCS)
{
    for(auto c: pCS){
        this->append(c);
    }
}

I went through the entire c++ tutorial on this website and don't recall any mention of this.
It is an excellent tutorial, but likely not 100% up to date.
If you are talking about the tutorial here at CPlusPlus, yeah, it ain't complete or up-to-date. It stopped being updated around the time C++14 was standardized.

Learn C++ is better IMO, and is up-dated on a regular basis.

Neither online tutorial is a complete overview of what C++ has to offer. That is where a reference site like cppreference comes in. Not for beginners to learn C or C++, though.
Topic archived. No new replies allowed.