Can you help me to get class inheritance working?

More OOP questions here.

I want to create a class called AudioSource, which will represent any source of audio data. This class will have no properties and provide no functionality. My intention is that I’ll extend it with subclasses for specific situations; for example, I might have such subclasses as WhiteNoise (which generates random data), and ToneGenerator (which generates a sine wave), FileAudioSource (which reads data from a file), or AudioMixer (which sums the outputs of several AudioSource objects into one).

Here’s the constructor I’ve come up with for the parent class:

function obj = AudioSource ()

  obj = class(struct([]), "AudioSource");


Next, I want to create one of the subclasses. I’ll start with “FileAudioSource”, which will specifically represent an audio file on disk opened for reading. It will have several properties, including the filename, the sample rate, a buffer of data, and so forth. Here’s what I’ve attempted as a contructor so far:

function obj = FileAudioSource (filename)

  obj.filename = filename;
  [, obj.sampleRate] = audioread(filename); # load in the entire file contents and store the sample rate
  obj.pos = 0;

  obj = class(obj, "FileAudioSource", AudioSource()); # third argument is an instance of the superclass


So, if I understand correctly, the third argument to class() needs to be an object of the superclass. Since my superclass has no attributes, I’ve just called its constructor directly with no arguments.

Now, when I try to invoke my FileAudioSource constructor, it fails with error: class: parent class dimension mismatch. I can’t find anything in the octave documentation that may relate to this, but if I check the Matlab documentation, at, I see that the size of the parent object is supposed to be either the size of the first argument (my obj struct) or be a scalar.

What does this mean? Do I have to enlarge my parent class with dummy variables to make it the same size as all its subclasses? Surely that wouldn’t make sense, because presumably in most situations subclasses will have additional attributes not present in the superclass. So I’m obviously missing something here.

Thanks in advance!

Never mind. I switched to classdef-style classes and this problem went away. :slight_smile:

The problem seems to be the empty struct initialization:

- obj = class(struct([]), "AudioSource");
+ obj = class(struct(), "AudioSource");

For example:

>> struct ()
ans =

  scalar structure containing the fields:

>> size (ans)
ans =

   1   1

>> struct ([])
ans =

  0x0 struct array containing the fields:
1 Like

Thank you! Unfortunately I can’t try your solution because I’ve already revamped everything to use classdef instead of class(). :open_mouth: