Constructor calls parent

Hi

I have a class witch inherit from another. I want that the child’s
constructor call the upper constructor before start his (sorry for my
bad english).

in C++ it would be :
MyClass::MyClass(options) : upperClass(options){

}

I don’t find how to write it in Ruby.

I have a class witch inherit from another. I want that the child’s
constructor call the upper constructor before start his (sorry for my
bad english).

in C++ it would be :
MyClass::MyClass(options) : upperClass(options){

}

I don’t find how to write it in Ruby.

class MySuperClass
def initialize(args)

end
end

class MyClass < MySuperClass
def initialize(args)
super # <- what you need
end
end

Regards,
Rimantas

On Sep 26, 2006, at 8:15 AM, David C. wrote:

I don’t find how to write it in Ruby.

class Parent
def initialize
puts “Parent#initialize called.”
end
end
=> nil

class Child < Parent
def initialize
super # call Parent#initialize with our parameters
puts “Child#initialize called.”
end
end
=> nil

Child.new
Parent#initialize called.
Child#initialize called.
=> #Child:0x326444

If you would rather pass no arguments to the parent, use super(). To
control which arguments are passed use this form: super(:passed,
“arguments”, 4, :parent).

Hope that helps.

James Edward G. II

thanks all !

David C. wrote:

Hi

I have a class witch inherit from another. I want that the child’s
constructor call the upper constructor before start his (sorry for my
bad english).

Hi David,

You use the #super method. If you don’t need to do any setup in your
class, just leave off the initialize method and it automatically calls
the superclass’s constructor. If you need to do some setup, use the
#super method in your subclass’s initialize constructor. If the
arguments to the superclass’s constructor are the same as the
subclass’s, just call super with no arguments. Otherwise pass it the
arguments for the superclass’s constructor.

class C
def initialize(x, y, z)
@x, @y, @z = x, y, z
end
end

no setup

class D < C
end

setup but same args to superclass

class D < C
def initialize(x, y, z)
super
end
end

setup but different args to superclass

class D < C
def initialize(x, y, z, a)
super(x, y, z)
@a = a
end
end

HTH,
Jordan

Hi,

At Tue, 26 Sep 2006 22:40:19 +0900,
MonkeeSage wrote in [ruby-talk:216481]:

You use the #super method.

super' is a keyword in Ruby, not a method. Of course, you can define a method namedsuper’, but you can’t call it without the receiver.

Nobuyoshi N. wrote:

super' is a keyword in Ruby, not a method. Of course, you can define a method namedsuper’, but you can’t call it without the receiver.

Ah, sorry! Thanks for making that clear.

Regards,
Jordan