C++ Constructor Question

Started by
4 comments, last by NoahAdler 19 years, 3 months ago
Greetings, Sorry if this is too simple of a question. Basically I am trying to understand a PLIB source file. ssgaTeapot is a class inherited from ssgaShape. Now, the constructor is defined as this: ssgaTeapot::ssgaTeapot(int nt):ssgaShape (nt){type=ssgaTypeTeapot();regenerate();} What does this mean exactly? I understand that the body is calling 2 functions. The part I don't exactly get is the ":ssgaShape (nt)" Thanks in advance!
Advertisement
It's an initializer list, normally used to initialize const variables in classes because they cannot be initialized in the body (they're const), and simply sets the variable to whatever is in parenthesis. So for this example ssgaShape is a variable of the class and is being initialized to the int nt.
It determines which constructor overload of ssgaShape to use. If it's omitted, it attempts to use the default constructor. If ssgaShape has no default constructor, then it must be explicitly specified as shown. Else how would you specify what gets passed in?

Hope this helps.
-bodisiw
ssgaTeapot::ssgaTeapot(int nt)          :ssgaShape (nt){     type=ssgaTypeTeapot();     regenerate();} 


ssgaTeapot inherits from ssgaShape, and it's just calling ssgaShape's constructor... Is there some other way to look at this?
Quote:Original post by NoahAdler
It determines which constructor overload of ssgaShape to use. If it's omitted, it attempts to use the default constructor. If ssgaShape has no default constructor, then it must be explicitly specified as shown. Else how would you specify what gets passed in?

Hope this helps.


So if I define an object of type ssgaTeapot, it will call the constructor of ssgaShape AND the constructor of ssgaTeapot (which is defined in the body)?
Quote:So if I define an object of type ssgaTeapot, it will call the constructor of ssgaShape AND the constructor of ssgaTeapot (which is defined in the body)?


Yep, assuming ssgaTeapot inherits from ssgaShape. For instance the following program:

#include <iostream>struct Base {  Base() { std::cout<<"Base()\n"; }  virtual ~Base() { std::cout<<"~Base()\n"; }};struct Derived : public Base {  Derived() { std::cout<<"Derived()\n"; }  virtual ~Derived() { std::cout<<"~Derived()\n"; }};int main() {  Derived d;}


The output will be
Base()Derived()~Derived()~Base()


This is standard inheritance rules. Base is responsible for initializing its own data, so its constructor needs to be called.
-bodisiw

This topic is closed to new replies.

Advertisement