calling inherited constructors

J

Joe, G.I.

I didn't write ClassA, but I'm trying to inherit from ClassA through
ClassB. I want to pass a string to the ClassA constructor but not sure
I'm calling ClassA's constructor correctly. I get the following g++
error ...

In constructor 'ClassB::ClassB(String&)':
../../../include/ClassB.h:19: error: expected `{' at end of input


ClassB *myClass = new ClassB("myClassName");

// ClassB.h
class ClassB : public ClassA {
ClassB(String &name) : ClassA(name);
}

// ClassB.cpp
ClassB::ClassB(String &name)
{
}

// ClassA constructor which I'm trying to pass the string to ...
ClassA::ClassA (const String & name)



What am I doing wrong here?
 
I

Ian Collins

Joe said:
I didn't write ClassA, but I'm trying to inherit from ClassA through
ClassB. I want to pass a string to the ClassA constructor but not sure
I'm calling ClassA's constructor correctly. I get the following g++
error ...

In constructor 'ClassB::ClassB(String&)':
../../../include/ClassB.h:19: error: expected `{' at end of input


ClassB *myClass = new ClassB("myClassName");

// ClassB.h
class ClassB : public ClassA {
ClassB(String &name) : ClassA(name);
}
class ClassB : public ClassA
{
ClassB(String &name);
};
// ClassB.cpp
ClassB::ClassB(String &name)
{
}
ClassB::ClassB(String &name)
: ClassA( name )
{
}
 
A

Andre Kostur

I didn't write ClassA, but I'm trying to inherit from ClassA through
ClassB. I want to pass a string to the ClassA constructor but not sure
I'm calling ClassA's constructor correctly. I get the following g++
error ...

In constructor 'ClassB::ClassB(String&)':
../../../include/ClassB.h:19: error: expected `{' at end of input


ClassB *myClass = new ClassB("myClassName");

// ClassB.h
class ClassB : public ClassA {
ClassB(String &name) : ClassA(name);
}

// ClassB.cpp
ClassB::ClassB(String &name)
{
}

// ClassA constructor which I'm trying to pass the string to ...
ClassA::ClassA (const String & name)



What am I doing wrong here?

Assuming you fix the minor issues (like the missing semicolon at the end of
the class declaration), the piece you've got wrong is that the initializer
list goes with the constructor definition, not the declaration:

class ClassB : public ClassA {
ClassB(String & name);
};

ClassB::ClassB(String & name) : ClassA(name) {}


Something else to consider... do you really want to pass the String by non-
const reference? Generally speaking, if you're passing stuff by reference,
you should probably pass it by const-reference (unless you have a specific
reason to pass it non-const...)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,586
Members
45,085
Latest member
cryptooseoagencies

Latest Threads

Top