![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Hobbyist Programmer
Join Date: Feb 2006
Posts: 155
Rep Power: 3
![]() |
class/constructor
I have to accomplish this weird task, no idea how to go about it.
there is a template class named "Scanner", and its constructor is used to open a file. and there is a class named "Parser", and it's supposed to take the filename from main.cpp and pass it to the class Scanner. Oh also, all the member functions of the Parser class needs to have access to the declaraton involving scanner within the parser class. I am more confused with the syntax than anything Trial I have had: I tried using Scanner <string> Si; inside the public section of the Parser class, then tried updating the "Si" in the Parser constructor so that Si now has the filename, it didnt work : Parser (string s)
{
Scanner <string> Si(s);
NT = Si.cget();
GlobalRootM = prog();
}I'm obviously doing something wrong with the syntax, but I dont know what! Oh, dont ask me why i am linking parser and scanner this way to get the filename (I have to!! lol) |
|
|
|
|
|
#2 |
|
Programming Guru
![]() Join Date: Jun 2005
Location: Adelaide, South Australia
Posts: 1,260
Rep Power: 5
![]() |
If I'm understanding you right, your class declaration looks something like this;
class Parser
{
public:
Parser(const std::string &);
private:
Scanner<std::string> Si;
};Assuming this is correct, then one way of implementing your constructor is outside your class declaration; Parser::Parser(const std::string &s) : Si(s)
{
NT = Si.get();
// etc
}A couple of additional notes; 1) If you have used "using namespace std;" within your class declaration (or in the header file that contains it), good practice says "don't do that". 2) If prog() is a virtual member function of class Parser, or if it calls virtual member functions, then it is usually a good idea to NOT call it from a constructor of class Parser. |
|
|
|
|
|
#3 |
|
Professional Programmer
Join Date: May 2006
Location: Maryland, USA
Posts: 306
Rep Power: 3
![]() |
Virtual functions overridden in a subclass do not get called from the constructor of the base class, only the base class versions get called. This is why its a good idea not to do that.
|
|
|
|
|
|
#4 |
|
Programmer
Join Date: May 2006
Location: Cambridge, UK
Posts: 85
Rep Power: 3
![]() |
AFAIK that is because the state of the subclass instance is somewhat up in the air while the baseclass constructor is executed.
(I couldn't help butting in :-)
__________________
Don't comment bad code - rewrite it. - The Elements of Programming Style (Kernighan & Plaugher) |
|
|
|
|
|
#5 | |
|
Programming Guru
![]() Join Date: Jun 2005
Location: Adelaide, South Australia
Posts: 1,260
Rep Power: 5
![]() |
Quote:
|
|
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|