They seemed to make sense to me, until I read somewhere than an example of a constructor is

std::ifstream myFile("filename.txt");

..the author went on to say that (obviously, in this example) they can be called after an object is instantiated, ie:

std::ifstream myFile;

// some code here

myFile.open("filename.txt")

This intuitively makes sense, as you may want to declare your variables near the top of your code, and initialize them later..

But if constructors always have the same name as the class itself, then why is myFile.open() a constructor?
And if I have a class CImgDisplay (for example), and I want to declare an object CImgDisplay main_disp;
then how do I know what name to call the constructor with later? Do I have to go digging through the header file?

Or is that ifstream example a bad example or something?

Sorry for the dumb question.. I've got 2 days to finish my project, and I've never done objects before.. according to all the books I have, the only way it can be done is by initializing it all in one go..

>But if constructors always have the same name as the class itself, then
>why is myFile.open() a constructor?
It's not a constructor. In that example the default constructor is used when you say std::ifstream myFile; . The default constructor doesn't open any file, so the regular member function open needs to be called.

In the first example, the overloaded constructor that takes a file name constructs the object and opens a file, so the open member function isn't needed.

I see.. so if an object is instantiated by naming it and putting arguments in brackets, then that's not necessarily a constructor?

So if the proper way to declare is

class object (arg1, arg2);

and I want to do it separately, such as

class object;

and then pass the two arguments later... then I have to look through the header file to find the appropriate method, yeah?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.