Main Content
Calling base class constructors Archive - Originally posted on "The Horse's Mouth" - 2008-10-03 07:13:33 - Graham Ellis
In all object oriented languages, you have a facility called inheritance where you can define one type of thing ("class of object") based on another, and the newly defined class ("subclass" or "extended class") takes the initial ("base") class as it starting point.
In your code for your base class, you'll have some logic which sets up new objects (a "constructor" method), and you'll have code in your extended classes through which you set up objects of that extended type. Almost inevitably, your extended objects will be pretty similar to your basic objects but they'll have a few extras, and so the writers of Object Oriented languages provide you with a way of calling the base class constructor within (or before) your extended class constructor . The base class is sometimes called the parent class. Let me translate that into an example in plainer English.
"A Train journey is a specialised type of public transport journey. If you're setting up a train journey, you'll want to set up a regular public transport journey within it first, with attributes like where it goes from and to, and at what time and who runs it. Then you will add some train extras such as how many carriages long it is"
How does this work in C++?
Train::Train(int nvh, int vhc, int xtrwa ) : PubT(nvh, vhc) {
tronly = xtrwa;
}
A Train is a PubT. When you create a train (with three parameters), you create first a PubT passing the first two parameters in to it, and them you perform the extra actions in the code block - which is saving the third parameter.
Course - C++ Programming
How does this work in Java?
public Train (int nvh, int vhc, int xtrwa) {
super (nvh,vhc);
this.tronly = xtrwa;
}
How does this work in Python?
def __init__(self,nvh,vhc,xtrwa):
pubt.__init__(self,nvh,vhc)
self.tronly = xtrwa
Course - Python Programming
This is old style classes; in new style classes, you'll call parent on the current class to avoid having to state the name of the parent class within the extended class definition.
How does this work in Perl?
In Perl, you "roll you own" ... it's so flexible and there are so many options it's almost untrue! Here's an example:
sub new {
my ($self,$nvh,$vhc,$xtrwa) = @_;
my $cc = new pubt($nvh,$vhc);
$cc->{"tronly"} = $xtrwa;
bless \%{$cc};
}
Course - Perl for Larger Projects
How does this work in [incr-Tcl]?
constructor {nvh vhc xtrwa} {
pubt::constructor $nvh $vhc } {
set tronly $xtrwa
}
}
Course - Tcl Basics and please let us know when you book that you would like us to add in strong coverage of Incr-Tcl
How does this work in PHP?
public function __construct($nvh, $vhc, $xtrwa) {
parent::__construct($nvh, $vhc);
$this->tronly = $xtrwa;
}
This example is for PHP 5. If you're still using PHP version 4, you'll call your constructor the same name as the name of the class, and call the base class constructor via the class name.
Course - Object Oriented PHP
def initialize(nvh, vhc, xtrwa)
super(nvh, vhc)
@tronly = xtrwa
end
How does this work in Lua?
Lua is a small language which provides you with facilities through which you can write OO like code but it is not strictly objects. You can set the metatable of a table [object] to the metatable of the table which you wish to be the parent, then modify it - thus emulating the facility that I'm talking about in this article.
Course - Lua Programming
Some other articles
Y112 - Objects - Intermediate Nesting decorators Defining an object that is a modified standard type in Python with in Python - examples of use, and of defining your own context Object and Static methods - what is the difference; example in Python 3 Setting up and tearing down with the Python with keyword Deciding whether to use parameters, conditional statements or subclasses Spike solution, refactoring into encapsulated object methods - good design practise A good example of recursion - a real use in Python Changing what operators do on objects - a comparison across different programming languages Object factories in C++, Python, PHP and Perl Python base and inherited classes, test harness and unit testing - new examples Python Properties - how and why Really Simple Class and Inheritance example in Python Inheritance, Composition and Associated objects - when to use which - Python example Backquote, backtic, str and repr in Python - conversion object to string Metaclasses (Python) and Metatables (Lua) Static variables in functions - and better ways using objects A demonstration of how many Python facilities work together A list of special method and attribute names in Python Python - some common questions answered in code examples Defining static methods in Python Should Python classes each be in their own file? The Light bulb moment when people see how Object Orientation works in real use Python decorators - your own, staticmethod and classmethod Mixins example in Python Multiple inheritance in Python - complete working example The Multiple Inheritance Conundrum, interfaces and mixins Methods that run on classes (static methods) in Python How do I set up a constant in Python? TypeError: super() argument 1 must be type, not classobj (Python) Python - fresh examples of all the fundamentals This article Equality, sameness and identity - Python Using a utility method to construct objects of different types - Python Python - formatting objects What are factory and singleton classes? __new__ v __init__ - python constructor alternatives? Practical polymorphism in action Pieces of Python Comparison of Object Oriented Philosophy - Python, Java, C++, Perl Think about your design even if you don't use full UML Class, static and unbound variables Overloading of operators on standard objects in Python Using a Python dictionary as a holder of object attributes U107 - Object Orientation - the Lua way Lua, Tcl, Python, C and C++ courses - at our Melksham HQ or on your site - forward from July 2017 Classic style OO code - in Lua Tables with values and code in Lua - looks like an object? Dot or Colon separator between table name and member in Lua - what is the difference? Metatables, Metamethods, classes and objects in Lua Is Lua an Object Oriented language? What is a metatable? How do I set one up? How do I use them? Lua Using Lua tables as objects Special __ methods you can use in Lua metatables Weak references in Lua - what are they, and why use them? Metaclasses (Python) and Metatables (Lua) Tables as Objects in Lua - a gentle introduction to data driven programming Private and Public - and things between __index and __newindex in Lua - metatable methods Lua Metatables Is Lua an Object Oriented language? Lua examples - coroutines, error handling, objects, etc A fresh example - objects the Lua way For Lua Programmers AND for Town Planners This article First class functions in Lua lead to powerful OO facilities If you are learning Lua, here are some more examples Towards Object Oriented Programming in Lua T245 - [incr-Tcl] Using Object Oriented Tcl and the Tk toolkit together - real life example Objects in Tcl - iTcl - updated first steps example Private and Public - and things between Introduction to Object Oriented Programming This article Object Oriented Tcl Think about your design even if you don't use full UML Object Orientation in Tcl - [incr-Tcl] P218 - More Objects Changing what operators do on objects - a comparison across different programming languages Object factories in C++, Python, PHP and Perl Using object orientation for non-physical objects Perl design patterns example Building an object based on another object in Perl Perl - calls to methods that use => - what do they mean? What do I mean when I add things in Perl? Learning Object Orientation in Perl through bananas and perhaps Moose Making Perl class definitions more conventional and shorter Some more advanced Perl examples from a recent course Different perl examples - some corners I rarely explore Igloos melt in the summer, but houses do not The Multiple Inheritance Conundrum, interfaces and mixins Calculation within objects - early, last minute, or cached? Operator overloading - redefining addition and other Perl tricks Nuclear Physics comes to our web site This article Factory method example - Perl Example of OO in Perl Object Oriented Programming in Perl - Course Perl for Larger Projects - Object Oriented Perl What are factory and singleton classes? -> , >= and => in Perl Comparison of Object Oriented Philosophy - Python, Java, C++, Perl Think about your design even if you don't use full UML NOT Gone phishing Changing @INC - where Perl loads its modules Packages in packages in Perl When to bless a Perl variable Bellringing and Programming and Objects and Perl J710 - Extending Classes and More Objects - from physical to virtual or abstract - Java Java Inheritance example - group of classes - step by step Philosophy behind object design - and how I applied in to a Java example Changing what operators do on objects - a comparison across different programming languages Splitting out code into name blocks for clarity and reusability What is a universal superclass? Java / Perl / Python / Other OO languages What methods are available on this Java object? Tips for writing a test program (Ruby / Python / Java) Abstract classes, Interfaces, PHP and Java Abstract Classes - Java This article Java - a demonstration of inheritance on just one page Teaching Object Oriented Java with Students and Ice Cream Java - using super to call a method in the parent class An example of Java Inheritance from scratch What are factory and singleton classes? Final, Finally and Finalize - three special words in Java Comparison of Object Oriented Philosophy - Python, Java, C++, Perl Think about your design even if you don't use full UML H108 - Objects in PHP Associative objects - one object within another. Caching results in an object for efficiency - avoiding re-calculation Singleton design pattern - examples and uses Changing what operators do on objects - a comparison across different programming languages Object factories in C++, Python, PHP and Perl Learning about Object Orientation in PHP - a new set of examples stdClass in PHP - using an object rather than an associative array Objects in PHP - Revision Caching Design Patterns Copying, duplicating, cloning an object in PHP Autoload in PHP How do classes relate to each other? Associated Classes Design Patterns - what are they? Why use them? Designing your application - using UML techniques Computer Graphics in PHP - World (incoming data) to Pixel (screen) conversion Catchable fatal error in PHP ... How to catch, and alternative solutions such as JSON Private and Public - and things between Getting the OO design write - with PHP a example Does copying a variable duplicate the contents? PHP - Object Oriented Design in use What is a factory? The Multiple Inheritance Conundrum, interfaces and mixins Static class members in PHP - a documented example Object Oriented Programming in PHP Shipping a test harness with your class in PHP Serialization - storing and reloading objects Abstract classes, Interfaces, PHP and Java Object Oriented programming - a practical design example PHP4 v PHP5 - Object Model Difference Cleaning up redundant objects When should I use OO techniques? PHP - getclass v instanceof Introduction to Object Oriented Programming Sorting objects in PHP This article Accounts in PHP - an OO demo OO PHP demonstration - comparing objects and more What are factory and singleton classes? Object Oriented Model - a summary of changes from PHP4 to PHP5 Cue the music, I'm happy. Build on what you already have with OO Planning a hotel refurb - an example of a Gant chart in PHP Think about your design even if you don't use full UML North, Norther and Northest - PHP 5 Objects Don't repeat code - use loops or functions Should I use structured or object oriented? PHP5 lets you say no PHP v Java Object Oriented Programming in PHP G997 - Newsletter Lead Articles Telling you something about us in just one line Public Open Source Training Courses running this summer and autumn in Melksham Open Source Training Centre and Courses for 2010 Weekend and Christmas Promotion - Well House Manor Hotel, Melksham C++, Python, and other training - do we use an IDE Walks in and around Melksham, Wiltshire Make your business a DESTINATION business How was my web site compromised? Book now for 2009 This article Upgrade from PHP 4 to PHP 5 - the TRY issue Python in an afternoon - a lecture for experienced programmers Cambidge - Tcl, Expect and Perl courses Letting new visitors know we provide training courses New trainee laptop fleet for our Open Source courses New software product for warmblooded programmers Well House Manor - feature comparison against the old place! Object Relation Mapping (ORM) Buffering output - why it is done and issues raised in Tcl, Perl, Python and PHP Graham Ellis - an Introduction One Thousand Posts and still going strong C234 - Further C++ Object Oriented features When do I use the this keyword in C++? Designing a base class and subclasses, and their extension, in C++ Changing what operators do on objects - a comparison across different programming languages Using a vector within an object - C++ Operator Overloading, Exceptions, Pointers, References and Templates in C++ - new examples from our courses Sigils - the characters on the start of variable names in Perl, Ruby and Fortran Bradshaw, Ben and Bill. And some C and C++ pointers and references too. C++ - putting the language elements together into a program Strings, Garbage Collection and Variable Scope in C++ Lots of things to do with and within a C++ class What are C++ references? Why use them? The Multiple Inheritance Conundrum, interfaces and mixins Multiple Inheritance in C++ - a complete example What does const mean? C and C++ Variables and pointers and references - C and C++ Variable Scope in C++ This article It can take more that one plus one to get two. Comparison of Object Oriented Philosophy - Python, Java, C++, Perl undefined reference to typeinfo - C++ error message Simple polymorphism example - C++ C233 - OO in C++ - beyond the basics Variables, Pointers and References - C and C++ When do I use the this keyword in C++? Designing a base class and subclasses, and their extension, in C++ Final examples for 2014 - and a look at our 2015 training course options Object factories in C++, Python, PHP and Perl Extended and Associated objects - what is the difference - C++ example Associated Classes - using objects of one class within another Destructor methods in C++ - a primer C++ - objects that are based on other objects, saving coding and adding robustness C and C++ - preprocess, compile, load, run - what each step is for Private and Public - and things between C++ - putting the language elements together into a program C++ objects - some short, single file demonstrations C++ - a complete example with polymorphism, and how to split it into project files Objects and Inheritance in C++ - an easy start Complete teaching example - C++, inheritance, polymorphism This article What a lot of files! (C++ / Polymorphism demo) C - structs and unions, C++ classes and polymorphism What are factory and singleton classes? C++ - just beyond the basics. More you can do Comparison of Object Oriented Philosophy - Python, Java, C++, Perl Simple polymorphism example - C++ References and Pointers in C++