suffi suffi - 1 month ago 11
C++ Question

Constructing objects in c++

So, I'm coming from Java, learning c++. I want to implement a program that can be called like this, provided by a test file (boots):

auto subject = anagram::anagram("diaper");
auto matches = subject.matches({"hello", "world", "zombies","pants"});
vector<string> expected;
BOOST_REQUIRE_EQUAL_COLLECTIONS(expected.begin(), expected.end(), matches.begin(), matches.end());


Do I get it right, that
anagram::anagram(...)
is a constructor, constructing an Object that provides the method
matches(...)
? Because in my Implementation (cf. below) I get an error saying something (not in english) like "constructor can not be called directly". I think there is something I do not understand about constructors in c++.

// this is part of my implementation of anagram.h
class anagram{

public:
anagram(const string a);
vector<string> matches(vector<string> &list);

private:
string a;
bool isAnagram(string s);
};


The only other thing I know is that
anagram::anagram(...)
could be a static method, with a return value that is similat to
this
, but that wouldn't make sense to me. So it would be nice if someone could explain this :)

Answer

One way it can work with syntax you have shown is if class anagram is placed in similary named namespace:

#include <string>
namespace anagram 
{
class anagram
{
  public:
    anagram(std::string s) {}
};
}

int main() 
{
    auto subject = anagram::anagram("diaper");
}

http://ideone.com/1OVhIz

Comments