Superclass method calling problem

hi

i have a problem:

my baseclass

class A
def initialize(b)
puts “Initialized A: #{b}”
end

# need to call this from B
def foo(a)
    puts "Foo A: #{a}"
end

end

my derived class

class B < A
def initialize(c)
super(c)
# need something here, like A::foo(c) ??
puts “Initialized B: #{c}”
end

def foo(d)
    puts "Foo B: #{d}"
end

end

I want that if i call B.new(10) that B is initialized and calls the old
function foo from class A (from its ancestor).
but i have to overload the foo function so simply calling foo(c) would not
work.

The Output should be:

x = B.new(10)
Initialized A: 10
Foo A: 10
Initialized B: 10

x.foo(20)
Foo B: 20

Any ideas ?

Thanks,

Peter

    def initialize(c)
        super(c)
    # need something here, like A::foo(c) ??
        puts "Initialized B: #{c}"
    end

Well, you can use an alias something like

pigeon% cat b.rb
#!/usr/bin/ruby
class A
   def initialize(b)
      puts "Initialized A: #{b}"
   end

   # need to call this from B
   def foo(a)
      puts "Foo A: #{a}"
   end
end

# my derived class
class B < A
   if method_defined?(:foo) && !method_defined?(:foo_a)
      alias foo_a foo
   end
   def initialize(c)
      super(c)
      # need something here, like A::foo(c) ??
      foo_a(c)
      puts "Initialized B: #{c}"
   end

   def foo(d)
      puts "Foo B: #{d}"
   end
end

x = B.new(10)
x.foo(20)
pigeon%

pigeon% b.rb
Initialized A: 10
Foo A: 10
Initialized B: 10
Foo B: 20
pigeon%

Guy Decoux

Hi Peter,

My “not-so-elegant” solution is to provide an extra parameter in B#foo:

----------------------------------------

my baseclass

class A
def initialize(b)
puts “Initialized A: #{b}”
end

# need to call this from B
def foo(a)
    puts "Foo A: #{a}"
end

end

my derived class

class B < A
def initialize(c)
super(c)
foo (c, true) # need an extra parameter here
puts “Initialized B: #{c}”
end

# need an extra parameter here
def foo(d, par = false)
    if par
        super (d)
    else
        puts "Foo B: #{d}"
    end
end

end

x = B.new(10)
x.foo (20)

----------------------------------------

Probably other people can provide a better solution.

I guess you miss the C++ scoping operator ::? :slight_smile:

Regards,

Bill

···

===========================================================================
Peter Schueller peter.schueller@solution-x.com wrote:

I want that if i call B.new(10) that B is initialized and calls the old
function foo from class A (from its ancestor).
but i have to overload the foo function so simply calling foo(c) would not
work.

The Output should be:

x = B.new(10)
Initialized A: 10
Foo A: 10
Initialized B: 10

x.foo(20)
Foo B: 20