FAQ Database Discussion Community


Is it safe to declare non-virtual destructor in the derived class

c++,inheritance,destructor,virtual-functions
In the program: struct A { virtual ~A(){ } }; struct B : A { ~B(){ } }; int main(){ } The Standard N4296::12.4/9: If a class has a base class with a virtual destructor, its destructor (whether user- or implicitly-declared) is virtual. So, the compiler will redeclare the destructor...

C++ multiple inheritance and virtual class [duplicate]

c++,inheritance
This question already has an answer here: C++ previous definition error 2 answers I'm trying to write a program with four classes: vehicle, car, airplane and flying car. Flying car inherits from car and airplane, car and airplane both inherit from vehicle. vehicle.h class vehicle { public: vehicle(); vehicle(char*,...

“Attempting to use an incompatible return type” with Interface Inheritance

java,inheritance,interface
I'm running into a problem with incompatible return types using inheritance. public interface A { } public interface B extends A { } public interface C { Map<String, A> getMapping(); } public interface D extends C { Map<String, B> getMapping(); } Is there a way to make this work? Right...

Passing derived class to base function

c++,inheritance,pass-by-reference,derived-class
I'm having trouble passing a derived class to a function which accepts the base class as argument. The base class is consists of "obstacles" which are to be placed on a "board" void Board::setvalue(int length, int width, Obstacle& obstacle); However, this causes the compiler to give the "no known conversion...

AngularJS: variable $scope inside a function appears undefined outside the function

javascript,angularjs,inheritance,angularjs-scope
I am new with AngularJS and I am stuck :\ NEED HELP, please! The purpose of the code below is to get a specific data (an integer) from a DB in order to build a doughnut chart. I run the function dataforGraphs() in order to get that value. But then,...

Trying to befriend a function of Derived in Base - Why doesn't it work?

c++,inheritance,friend,forward-declaration,friend-function
My first post here. I have two classes - Base and Derived (derived publicly from Base). In Derived, I have a function printAsFriend. Compiler is unhappy with this. Why? Methods in other classes can be befriended. Why doesn't it work with a derived class? It works OK if I remove...

Nested pointer instead of inheritance

c++,oop,inheritance
I have some source code in C++, which I need to understand and extend / modify. According to the documentation some classes are planned as base and derived classes to implement an inheritance mechanism. When I look into source code, the derived class is not derived from the base class...

Reuse variables in base class in derived class: Scala

scala,inheritance
Consider a code segment trait MyTrait{ val x: Int = 0 } case class MyClass(y: Int = 1, z: Int = 2) extends MyTrait //script starts now val myClass = MyClass(3,4) myClass.copy(x, 5) Why does this not work? It says undefined variable x. I know it can be written like...

Access Parent Class without declaring property

.net,class,inheritance
I know this is a very silly thing to ask, but is this possible? Says I have this class Class A { string propertyA; Public A() { // do something here } } Then this : Class B { A classA; string propertyB; } Normally I would do this :...

Calling a Base Class Function through Derived Class Object [duplicate]

c++,inheritance
This question already has an answer here: Why does an overridden function in the derived class hide other overloads of the base class? 3 answers Why won't the compiler call the base class function (parameterized one) through the derived class object? The derived class inherits the function from the...

AbstractMethodError when mixing in trait nested in object - only when compiled and imported

scala,inheritance,trait
Consider the following code: object Impls { trait ConcreteImpl { type Foo = Int def foo = 1 } } trait Base { type Foo def foo: Foo } I am interested in the expression (new Base with Impls.ConcreteImpl).foo When I paste the above code in the REPL, or run...

JavaScript- Remove object from parent array with an object's method

javascript,arrays,inheritance,circular-reference
I have a parent object that stores an array of children and calls some of their methods. var Parent = function () { this.children = [] this.addChildren(); } Parent.prototype.addChildren = function () { for (var i=0; i < 5; i++) { this.children.push(new Child()); } this.alterChildren(); } Parent.prototype.alterChildren = function ()...

How can I override the member of (->) operator of a base class

c++,qt,inheritance,overloading,operator-keyword
Background: I have Qt generated UI classes with no common ancestor. I am subclassing a class (say, "Door") that uses one of these UI classes, and the derived class ("OakDoor") will use a different UI class, although much of the UI elements will have the same name. Until now I...

about Multiple inheritance and virtual inheritance

c++,inheritance
I don't quite understand Multiple inheritance and virtual inheritance. plz help me. Here is my little test: class Test1 {}; class Test21 : public Test1 {}; class Test22 : public Test1 {}; class Test3 : public Test21, public Test22 {}; int main() { Test1 * t1 = new Test3(); delete...

Java inheritance confusion, superclass and subclass member variable having same name

java,inheritance,this
On running this code class c1 { int ci = 1; } class c2 extends c1 { int ci = 2; } class inheritanceTest { public static void main(String args[]) { c1 c1reftoc2 = new c2(); System.out.println(c1reftoc2.ci); } } Output is 1. So i guess that a subclass object with...

python class factory inherit random parent

python,python-2.7,inheritance,factory
I have some code like this: class Person(object): def drive(self, f, t): raise NotImplementedError class John(Person): def drive(self, f, t): print "John drove from %s to %s" % (f,t) class Kyle(Person): def drive(self, f, t): print "Kyle drove from %s to %s" % (f,t) class RandomPerson(Person): # instansiate either John...

Inheritance classes (Java), explicit constructor error message

java,inheritance,compilation,extends
so I am trying to learn about inheritance classes. First I created a class called Box to calculate the area of the box. Then I created a TestBox Class in which I have created a box object called fedEx. Box Class: public class Box { private String boxName; public void...

Name lookup of qualified base class

c++,inheritance,name-lookup
Consider this code: #include <iostream> namespace D { struct S { S(){std::cout << "D::S\n";} }; } struct S { S(){std::cout << "S\n";} }; struct X: D::S { X(): S() {} // (1) // X(): D::S() {} // (2) void f() { S s; } }; int main() { X x;...

Cannot understand templates and constructor-related error

c++,templates,inheritance,constructor
#include <iostream> #include <vector> #include <string> using namespace std; enum class demo_initialize { a = 1, b, c, d }; class Base { public: Base(demo_initialize initialize) : mInitialize(initialize) {} protected: demo_initialize mInitialize; }; template <typename T> class Derived : public Base { public: Derived(T &value, demo_initialize initialize = demo_initialize::a) :...

Java alternative for empty overridden method in sub class

java,android,inheritance,abstract-class
I have the following class hierarchy: BaseActivity: public abstract class BaseActivity extends AppCompatActivity { protected abstract void bindView(); } ASubActivity: public class ASubActivity extends BaseActivity { @Override protected void bindView() { //No implementation } } BSubActivity: public class BSubActivity extends BaseActivity { private Toolbar toolbar; @Override protected void bindView() {...

C# How i use linq with explicit interface attribute?

c#,linq,inheritance,interface,explicit
i have one class with two inheritance interfaces and yours attributes are explicits because both have some equals attributes, so, i need use LINQ with this class, but i can't access the explicits attributes when i use "select new Foo" ... look the case: public class QuestaoMontaProva : IQuestao, IExercicio...

Inheriting defaultProps from superclass in React

inheritance,reactjs,ecmascript-6
I think some props, like "theme", are so universal among components that it makes sense to extract their handling (to a superclass). Then it follows that their default value also belongs there. However, using React this doesn't seem possible: class Base extends React.Component { bgColor() { switch (this.props.theme) { case...

syntax for calling a method on a member with multiple instances

c++11,inheritance,c++14
I the following case template<typename T> class base{ public: void test(){} }; template<typename T> class helper{ public: base<T> t; }; template<typename T, typename ... Ts> class holder: public helper<T>, helper<Ts>... { }; int main(int argc, char *argv[]){ holder<int, short, long> h; h.t.test(); // of course, error here } Which compiles...

What is this thing called in Java?

java,oop,object,inheritance,immutability
Google isn't being very friendly today, and I'm researching some OOP techniques I've not used in the past. Basically, I've noticed some libraries have variables with preset choices, like new Website(Websites.STACKOVERFLOW). What is that called, when you've got apparently immutable values like that? What if I want to create my...

Can adhering to the JavaBeans naming standard aid in achieving encapsulation?

java,oop,inheritance,coupling,cohesion
Is it possible that java beans naming standards help in achieving encapsulation? Isn't it the access modifier that helps in encapsulation? ...

Python inheritance program

python,inheritance
Error is: Equilateral object has no attribute angle1. please suggest how to fix this error and also please explain how self works. I am confused where to use self and where to not class Triangle(object): number_of_sides=3 def __init__(self,angle1,angle2,angle3): self.angle1=angle1 self.angle2=angle2 self.angle3=angle3 def check_angles(self): if self.angle1+self.angle2+self.angle3==180: return True else: return False...

Do I need to reimplement all the constructor of a base class even if a derived class has no member variables?

c++,inheritance,constructor
Let's assume I have a base class class Base { public: Base(); Base(int i, double j); Base(int i, double j, char ch); virtual void print(); private: int m; double l; char n; }; And I want to derive a class which overrides the print function but apart from that is...

JavaScript inheritance example returning undefined [duplicate]

javascript,inheritance
This question already has an answer here: Chrome/Firefox console.log always prepends a line saying undefined 2 answers I copied most of the code from an MDN article on .create() with some slight modification: // superclass function Shape() { this.x = 0; this.y = 0; }; // superclass method Shape.prototype.move...

What makes the object.prototype to the constructor function if he has no name? [duplicate]

javascript,function,class,inheritance,prototype
This question already has an answer here: Defining a Javascript prototype 5 answers My following code is this: var triangle = {a:1, b:2, c:3}; function constructorFunction() { this.color = "red"; } constructorFunction.prototype = triangle; I know that the prototype keyword extends classes in this syntax: Object.prototype.method = function() {}...

Using Getters and Setters in Base Activity Android

java,android,inheritance,android-activity
I made a generic activity which I am extending from in my main activity. I want to be able to change the String Variable in the base activity. See below. public abstract class BaseActivity extends ActionBarActivity { private String name; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.sidedrawer); TextView tv=(TextView)...

PHP Reflection: How to know if a method/property/constant is inherited from trait?

php,inheritance,reflection,traits,trait
I want to exclude all inherited methods from trait(s) from the list that are not overriden in a class So how to know if a class member is inherited from trait? Yes, I can check it like this: if ($trait->hasMethod($methodName) || $ref->getTraitAliases()[$methodName] !== null) { // } But what if...

JS Inheritance and mutating prototype

javascript,inheritance,prototype
AFAIK, JS provides inheriatnce by means of assigning a prototype chain to a newly created object. So, the code below seems to be the correct way to me: function Animal(name){ this.name = name; } Animal.prototype.getName = function(){return this.name;}; function Cat(){ Animal.apply(this, arguments); } Cat.prototype = Object.create(Animal.prototype); Cat.prototype.constructor = Cat; Cat.prototype.sayHi...

JavaScript inheritance Object.create() not working as expected

javascript,inheritance
I have: Master object function Fruit() { this.type = "fruit"; } Sub-object: function Bannana() { this.color = "yellow"; } Inherit master properties Bannana.prototype = Object.create( Fruit.prototype ); var myBanana = new Bannana(); console.log( myBanana.type ); Outputs: undefined. Why is this not displaying "fruit" as the outcome?...

How do I change part of a parent class's constructor when inheriting from it?

java,inheritance,subclass
I've got some class and I want to make an object out of it. However, this class has a property set in its constructor that makes it unusable for me. I cannot edit this class's code as it exists in a very tight codebase. This property cannot be changed after...

C++ call a child's method from a vector of parents?

c++,class,inheritance,polymorphism
Say that you have the following class: class Parent { // methods and members go here }; then you create a child based on the parent: class Child : public Parent { public: someFunction(); }; Now class Parent doesn't have someFunction() but class Child does. Say that you have a...

WCF reusing types with inheritance - cannot generate client code

.net,wcf,inheritance,datacontract
I was just getting an error message in Visual Studio 2013 stating "Failed to generate code for the service reference" when trying to update my service reference after adding a base class to a couple of my existing data contracts. For my service, I generate a client data contracts assembly...

Interface for Child Class that Inherits from parent class without reimplementing parent class

c#,oop,inheritance,interface
Currently I have the following: public class ChildClass : ParentClass {... ParentClass implements an interface as follows (I need ParentClass to be instantiated and therefore can't be abstract): public class ParentClass : IParentClass {... I also want child class to implement an interface so that I can mock this class...

Django: MTI get list of child classes

python,django,inheritance
Is there a way to get all child classes of a django multi table inheritance? Example: class Parent(models.Model): pass class ChildOne(Parent): pass class ChildTwo(Parent): pass I need a classmethod which returns [ChildOne, ChildTwo] BTW: This question is not about automatic down casting :-)...

how to use inheritence in ArrayList in java? [duplicate]

java,inheritance
This question already has an answer here: Why we can't do List<Parent> mylist = ArrayList<child>(); 2 answers I hava a class called QGNode that extends GNode and a class QGraph that extends Graph. In QGNode constructor when I call super constructor with an argument ArrayList<QGNode> an error occurs. Am...

Subclass as delegate of superclass

ios,objective-c,inheritance,uiviewcontroller,delegates
I have class ImageViewController. It has delegate: @protocol ImageViewControllerDelegate @optional - (void)singleTapGestureRecognizer:(UITapGestureRecognizer *)gesture; - (void)imageDidLoaded; I also have class AttachmentViewController that subclass of ImageViewController. In that class I want to get event then image property in changed. So here is my code of it change: - (void)setImage:(UIImage *)image { //...

Method chaining + inheritance 2 or more times

java,inheritance,chaining
I wan't to be able to method chain multiple vector class that build on top of each other. I want to be able to extend that class. Here is the 2d one: public class Vec2 < C extends Vec2 > { public double x, y; public Vec2() { } public...

Static interface equivalent C#

c#,inheritance,interface,static
I've worked with singletons in the past and I'm aware it's a solution for some people who are trying solve the static interface problem. In my case, I can't really use a singleton because I have an external class that I'm inheriting from and I have no control over this...

Understanding inheritance in practice. Printing values of an instance

python,class,inheritance,printing,instances
I have a class of Agents with a working __str__ method. I have a class of Family(Agents). The Family is structured as a dictionary with the Agent ID as key. After allocating agents to families, I iterate over my_families: When I print members.keys(), I get the correct keys. When I...

Inherit jQuery-like pattern

javascript,inheritance
Given the following code (jQuery pattern, I suppose): function child(){ return new child.methods.init(); } child.methods = child.prototype = { init: function(){ return this; }, test: function(){ console.log('test'); return this; } } //this code doesn't work child.methods.prototype = { test1: function(){ console.log('test1'); return this; } } child.methods.init.prototype = child.methods; //Using child...

How to call back an Object created in Python

python,list,object,inheritance
I have created several Objects in Python But when I try to recall them back I am Getting an error called "'int' Object has no attribute" Please consider that Parameters VehicleID,VehPosition,VehSpeed are constantly being updated by a program. What I want is to store all the data in separate Objects....

Android must implement the inherited abstract method

java,android,inheritance
I have downloaded project with this function where it works well, but when I coppied this function into my project, I get errors : The type new AsyncHttpResponseHandler(){} must implement the inherited abstract method AsyncHttpResponseHandler.onSuccess(int, Header[], byte[]) The method onSuccess(String) of type new AsyncHttpResponseHandler(){} must override or implement a supertype...

Enum inheritance conflict

c++,inheritance,enums
Suppose to have a base class that defines an enum like the following in its header file: class Base{ public: Base(); enum MyEnum1{ A_VALUE=1, B_VALUE=2 }; }; And a derived class that defines in a different enum the same variables but with different values: class Derived : public Base{ public:...

How can I access the members of a subclass from a superclass with a different constructor?

c++,inheritance,constructor,subclass,superclass
I have the following class and typedef: class Object { protected: long int id; public: Object(void); ~Object(void) {}; long int get_id(void); }; typedef map<string, Object> obj_map; And then I have its child: class Image: public Object { private: path full_path; int x; int y; img image; public: Image(path p, int...

Inheritance and Polymorphism in C#

c#,inheritance,polymorphism
There's a simple question, What will the program print to the console? I never thought that I could be wrong as much as I was with this piece of code. It behaved the other way around of what my logic expected from it. If someone could please enlighten the reason...

What happens when a method is overridden in Java?

java,inheritance,method-overriding
When a predefined method in Java is overridden... Only the method signature must be same Both method signature and inheritance must be same What is the answer? 1 or 2 I know that when we override the method in superclass, the method signature should be the same. But what about...

c++ expected template-name before ‘<’ token error [closed]

c++,templates,ubuntu,inheritance,g++
I´ve browser other similar topics and did not find answer for my problem... Here are my classes, a base one and a derived one: Base.hpp namespace test { template<class T> class Base { public: Base(); virtual ~Base(); }; } Base.cpp #include "Base.hpp" namespace test { template<class T> Base<T>::Base() { //...

Actual class of object reference

java,oop,inheritance,polymorphism,instanceof
Given three classes A, B, and C, where B is a subclass of A, and C is a subclass of B. (a) (o instanceof B) && (!(o instanceof A)) (b) (o instanceof B) && (!(o instanceof C)) (c) !((o instanceof A) || (o instanceof B)) (d) (o instanceof B) (e)...

C++ inheritance and virtual funcions

c++,function,class,inheritance,virtual
Here is my task: Design classes Circle and Square which are inherited from class Shape (which contains center of gravity which is common characteristic for all shapes, function for moving center of gravity for specific value and virtual functions circumference, area and read). Classes should have specific functions for calculating...

Convert List to typeof UnderlyingSystemType

c#,list,inheritance,reflection,dynamic-linq
I am currently working on code that is using dynamic-linq, I ran into a problem when using a List<BaseClass>, where the list actually contains a list of the Person Class. When I execute the following code I get a ParseException: var list = new List<BaseClass>(); list.Add(new Person { FirstName =...

Can you set pointer to derived class after you set some values in the base class?

c++,class,inheritance
I am new to c++ (I am using visual studio 2013) and I started experimenting with classes and inheritance. So I came up with a question which I can not find any anwser. Lets say we have this class: #include <iostream> using namespace std; class base{ protected: int var; public:...

Why does util.inherits create a new object that inherits from the super constructor's prototype? [duplicate]

javascript,node.js,inheritance,prototype
This question already has an answer here: Prototype copy vs Object.create() vs new 2 answers In the source for util.inherits they call object.create to create a new object whose prototype is the prototype of the super constructor. ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true,...

Abstract methods in Dart

inheritance,dart,dart-editor,abstract-methods
I'm implementing an inheritance hierarchy in which derived-class construction consists only of a call to the base-class constructor. The base-class constructor then calls method(s) implemented only in the derived-class. I have a basic implementation, but DartEditor of course complains about the missing methods in the base class. How can I...

How to make existing forms deriven from a base form in VB.net

vb.net,inheritance
I have an existing project in VB.net with many Windows forms.I want to change all forms to deriven from a base form created in a class library. is there any way to do so? if i do inheritance with a code like this the designer dose not show the child...

Getting Super's property value instead of actual object

java,inheritance
I have the following: Public Abstract class Entity protected int damagePoints = 0; public getDamagePoints() { return this.damagePoints; } Public abstract class IA extends Entity Public class Zombie extends IA implements Attacker { protected int damagePoints = 40; } Public class Engineer extends Entity implements DamageReceiver; Public interface Attacker {...

Ambiguous mapping found when I use extends clause

java,spring-mvc,inheritance,annotations
I have a CustomerController and CustomerCardController classes that extend CrudMethods class. I choose so, because these two controller use the same methods (getFileCustomer() is one of these). And I thought that it had been better use the inheritance to save code's rows. CustomerController @Controller public class CustomerController extends CrudMethods {...

Java dynamic binding calling method of parent class

java,inheritance,method-overriding
Below is the code which I am trying to analyze. class Acc{ public void aMethod(List<Integer> A){ System.out.println(A.toString()); } } class Back extends Acc{ public void aMethod(String A){ System.out.println(A); } } Here if I invoke it as Acc a = new Back(); a.aMethod(list); But upon debugging the method of parent class...

Define generic function type

generics,inheritance,anonymous-function,nim
Given the following snippet: type Base = object of RootObj Consume*[T: Base] = proc(e: T): bool I want to define several types from base and base consumer for it, like this: type BaseOne = object of Base ConsumeOne = Consume[BaseOne] Now, when i create a new ConsumeOne: let co: ConsumeOne...

Does my UoW class need to implement IDisposable if my BaseUow already implements it? [duplicate]

c#,inheritance,multiple-inheritance,idisposable,unit-of-work
This question already has an answer here: Implementing IDisposable on a subclass when the parent also implements IDisposable 5 answers I have created a base class for my Unit of Work called BaseUoW that inherits IDisposable like so: public class BaseUoW : IDisposable { } My question is... If...

What are the advantages of explicit interface implementation in C#? [duplicate]

c#,inheritance,interface,implementation
This question already has an answer here: C# Interfaces. Implicit implementation versus Explicit implementation 11 answers C# supports built-in mechanism for differentiating methods that have the same names. Here is a simple example below shows how it works: interface IVehicle{ //identify vehicle by model, make, year void IdentifySelf(); }...

Global class comparison with inheritance

c++,class,inheritance,comparison
I am writing global class comparison functions with operator== for a large framework where classes tend to inherit several classes or have deep inheritance (class A inherits from B, B inherits from C, etc.). In order to make things manageable I figured I would have a comparison functions for base...

Java inheritance and Scope of variable

java,inheritance,scope
The Program is: class A { int i = 10; } class B extends A { int j = 20; } class C extends B { int k = 30; } class D extends C { int m = 40; } public class asg2 { public static void main(String[] args)...

Creating a generic / abstract “DBContext” Class for shared functionality among different DBs

c#,database,generics,inheritance,abstract-class
I am working on a C# project that is pulling data from SQL Server, ODBC data-sources and Oracle Databases at different times. At this point, I have created 3 different classes - Once for each type of DB access. However, I am seeing that 95% of the code is identical...

Can inherited method access subclass fields in Java

java,inheritance,methods
I'm having trouble understanding inheritance. In the code below, why doesn't the inherited method access the field in the subclass? Is there any way to access the subclass field without overriding the inherited method? class Fish { private String fishType = "Fish"; public String getFishType() { return fishType; } }...

Scala child class fails to recognize a generic map in the parent?

scala,inheritance
I have the a code snippet which looks as follows: abstract class MultipleOutputWriter { protected def writers: collection.mutable.Map[Any, OutputStream] def write(basePath: String, value: Any) def close = writers.values.foreach(_.close) } class LocalMultipleOutputWriter extends MultipleOutputWriter { protected val writers = collection.mutable.Map[String, FileOutputStream]() def write(key: String, value: Any) = { //some implementation }...

Qt Cannot access *ui pointer from inheriting class

c++,qt,user-interface,inheritance,objective-c++
I am trying to write an application where I would have a generic dialog window and specific dialog windows that would inherit some basic functionalities from the generic one. I am not sure this is the best approach for this, but this is how I did it (The CGenericProject class...

Why can't class be destructed in polymorphism C++

c++,inheritance,polymorphism
I have the problem with using the polymorphism. The code here: class A { public: A() {cout << "construct a" << endl;} virtual ~A() {cout << "destroy a" << endl;} }; class B : public A{ public: B() {cout << "construct b" << endl;} ~B() {cout << "destroy b" <<...

Why put methods on the prototype of a class instead of declaring them in the constructor? [duplicate]

javascript,node.js,inheritance,prototype
This question already has an answer here: Use of 'prototype' vs. 'this' in JavaScript? 10 answers I'm trying to learn more about prototypal inheritance and I'm a little confused about the difference between adding methods to the prototype and adding them to the instance. Why would I do one...

Virtual function implemented as template in derived class

c++,templates,inheritance
Having following code: struct Base { virtual void print(int x) = 0; virtual void print(float x) = 0; }; struct Derived : public Base { template<typename T> void print(T x) { std::cout<<x<<std::endl; } }; Is it possible to do some C++ black magic(explicit instantiation for those types, some smart using,...

Multiple constructor inheritance

c++,inheritance,constructor
I'm trying to make two smaller constructors that can be called on their own, then make one larger constructor which allows you to do everything at once by simply calling the two other constructors. Example of my code: Foo::Foo(bool someVar, int someOtherVar, int fooBar) : Foo(someOtherVar, fooBar), Foo(someVar) {} Foo::Foo(bool...

How to make methods from parent class use a different variable?

c++,inheritance
I have a class like this: class A { protected: class Node { public: int x; Node* next; }; Node* root; . . . }; And a lot of methods using this "root". Now, say I want to inherit from A class, and make all the methods use a "better"...

Best practice to set large amount of properties in C# base class from derived class

c#,inheritance,polymorphism
I'm working on refactoring some legacy code, and have a large set of data objects that share the same properties and fields. I'm also doing some reading on refactoring and at first glance it looks like I should use Extract Superclass. Is this a good idea when all I'm combining...

Explain the time complexity of these grouping functions

c++,algorithm,inheritance,time-complexity
Here I have 800 derived classes of Base and a list of 8000000 objects of these types, which can be of any order. The goal is to separate the list into the 800 types as efficiently as possible. Here I have written two functions to do that. The first is...

How to implement methods of an abstract class? (Java)

java,inheritance,polymorphism
I am trying to use the methods from an abstract class that is implementing an interface. I keep getting a null pointer exception when I call upon a method and I am not sure why. Any ideas? Thanks. package start; public class Automobile extends Vehicle { // code with main...

Can't acces protected member

c++,inheritance
I have some difficulties understanding the following code. I have 3 classes: A, B and C. A has a private x of type int. B inherits A and everything from it. C inherits from B but protected. This means that both X and Y become inaccessible in class C. Also,...

Chaining through class hierarchy wihout calling `super` or inventing new names

ruby,inheritance
I have methods that use super: class A def say txt puts "A.say from #{self}: #{txt}" end def run puts "A.run from #{self}: I am preparing something here..." end end class B < A def run super say 'I am B, adding 1' say 'I am B, adding 2' end...

Java: Inheriting method with return type

java,inheritance,return
The Class3 class extends to Class1 class. In Class3, the method should return the total of the bonus and the salary and Class1 inherits from Class3 and displays the total and calculates the yearly salary by multiplying the total by 12. The problem is that the output which is I...

SIGSEGV with std::map of pointers to template objects

c++,templates,inheritance,g++,stdmap
I need to keep a std::map of pointers to templated objects. To get rid of templates, I use a common untemplated base class. When running the code, I get a SIGSEGV signal. Debugging shows that the problem arises with statement data_[id] = s; It could be a problem related to...

base class pointer, invoke method based on derived type

c++,oop,inheritance,polymorphism
I understand that the following code doesn't work -- can't convert base to foo. Is there something I can do, or some pattern to employ which would get me close the behavior I'm trying to achieve in the code below? IOW, if I have a base class pointer to a...

C# Explicitly override virtual interface method of base type

c#,inheritance,override
I have an abstract class DataBase which is used as base class for different types of data, such as simple value types (byte, int, string etc.) and more complex data structures like DataList and DataDictionary. DataList implements IList<DataBase> and DataDictionary implements IDictionary<string, DataBase>. For simplicity's sake, I went ahead and...

Why this code doesn't call the subclass? Inheritance in Java

java,inheritance
public class Parent { public void printParent() { System.out.println("I am the Parent"); System.out.println("----this is ::---" + this); this.printChild(); } private void printChild() { System.out.println("This is my child"); } } public class Child extends Parent { private void printChild() { System.out.println("I am the child"); } } public class RelationshipTester { @Test...

How can I return the array object from Array's prototype function?

javascript,arrays,inheritance,prototype,chaining
I have a programming exercise to create two prototypes of Array, they are both functions. I have put my code below. One will be called on the other as shown in the last line. I am trying to get the second function to modify the value that would have been...

Is dynamic_casting through inheritance hierarchy bad practice?

c++,oop,inheritance,casting
I have got the following data structure: class Element { std::string getType(); std::string getId(); virtual std::vector<Element*> getChildren(); } class A : public Element { void addA(const A *a); void addB(const B *b); void addC(const C *c); std::vector<Element*> getChildren(); } class B : public Element { void addB(const B *b); void...

Why is 1_2_3_4 a valid integer literal in java? [duplicate]

java,oop,inheritance,integer,literals
This question already has an answer here: Meaning of 0_0 in Java 7 [duplicate] 3 answers Wierd Syntax - Underscores between digits 1 answer Why does the following work? int a=1_2_3_4; System.out.println(a); // 1234 ...

Vector of objects from different classes

c++,class,object,inheritance,vector
I'm trying to create a vector containing objects from different classes, derived from a base class. Following answers to this question I've the following code which tries four different ways (commented out below); none of which will compile: class observable { public: virtual void observe(alglib::complex_1d_array)=0; observable() { } }; class...

Visual C++ - Virtual method is not overriden

c++,templates,inheritance,polymorphism,visual-studio-2015
I have two classes: template <class T> class TArray { public: TArray& operator =(const TArray &array) { return Copy(array); } virtual TArray& Copy(const TArray &array) { ... } } class TString : public TArray<TCHAR> { public: TString& Copy(const TString &string) { ... } } Classes also have needed constructors. But...

Returning `this` in a super method of inherited class

java,inheritance,polymorphism,this
let's say i have class A and class B which extends A, here are the classes: A: public class A { public int x; public static int y; public A(int x, int y) { this.x = x; this.y = y; } public int getX() { return x; } public static...

Inheritance: Set Values of Abstract Dictionary

c#,.net,inheritance,dictionary
I am currently working on a small project that includes an abstract baseclass of sorts, which defines some methods that require a dictionary. Yet the dicitionary is individual for each derived class. Therefore I defined the dictionary in my baseclass as follows: abstract internal Dictionary<string, column> columnNames { get; }...

Java 8 - Call interface's default method with double colon syntax

java,inheritance,lambda,java-8
I'm delving into the Java 8 innovations, and I'm trying to call a default method which I implement in a high-level interface, even when a subclass overrides it. I would have no problem going back to implementing a Comparator in my BusinessLogic class, but I was wondering if there's some...

I am having problems understanding inheritance and getting multiple classes to work together?

c++,inheritance,polymorphism
This is an assignment for my class. I am supposed to have two classes--salaried and hourly-- which both need to inherit from another class employee. When I compile my code I get no errors but when I run my program, only the header and the netpay functions produce any output....

How to determine an object's class in Java?

java,inheritance
How to determine an object's class in Java? Class B and class C extend class A. This is a method implementation in class D called dmethod(object of B or C) ,it except a single parameter that can be object of B or C. The calling methods can be dmethod(B object)...

What is the class of keywords like def, alias, and begin in Ruby, if any?

ruby,class,inheritance,keyword,superclass
As far as I understand, everything in Ruby is an object, and every object has a superclass, except BasicObject, which is at the top of the inheritance tree. What is the superclass of keywords like def, begin, and alias?...

Subclass of Django Model Not Accessible from Superclass

python,django,inheritance,model
I'm trying to create an inherited model in Django like that below. I should be able to call, for an instance superclass = Superclass(), I should be able to call superclass.subclass, and access the requisite fields. When I do that, I'm told that '1 argument was expected, and 8 were...

How to get rid of duplicate code in derived classes?

c++,oop,inheritance,override
I have a class hierarchy like: class A { list<A*> children; public: void update() { do_something(); update_current(); for(auto child : children) children->update(); } protected: virtual void update_current() {}; }; class B : public A { protected: void update_current() override { do_something_important(); }; }; class C1 : public B { protected:...

How to subclass when creating an object indirectly

python,class,inheritance
I'd like to add some functionality to the html trees coming from lxml. Thus I thought to add a class, using super().__init__() and add the extra functionality, such as adding the depth to each node, adding a boolean for isLeafNode, and implementing a view method. That's where the problem starts,...

JavaScript get prototype of object

javascript,inheritance
I have: var person = { kind: 'person' }; // create new object specifying the prototype as person var zack = Object.create( person ); console.log( Object.getPrototypeOf(zack) ); Output: Object {kind: "person"} Why does it not output person?...