Search Results

Search found 1494 results on 60 pages for 'prototypal inheritance'.

Page 10/60 | < Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >

  • Java inheritance question

    - by user247866
    So I have 3 classes. Abstract class A Class B extends class A independent Class C In class D that contains the main method, I create a list of instances of class B List<B> b = method-call();` // the method returns a list of instances of class B Now in class C I have one method that is common to both A and B, and hence I don't want to duplicate it. I want to have one method that takes as input an instance of class A, as follows: public void some-method(LIst<A> a) However, when I do: C c = new C(). c. some-method(b) I get an error that some-method is not applicable for the argument List, instead it's expecting to get List. Is there a good way to fix this problem? Many thanks!

    Read the article

  • Why avoid Java Inheritance "Extends"

    - by newbie
    Good day! Jame Gosling said “You should avoid implementation inheritance whenever possible.” and instead, use interface inheritance. But why? How can we avoid inheriting the structure of an object using the keyword "extends", and at the same time make our code Object Oriented? Could someone please give an Object Oriented example illustrating this concept in a scenario like "ordering a book in a bookstore?" Thank you in advance.

    Read the article

  • How to implement Template Inheritance (like Django?) in PHP5

    - by anonymous coward
    Is there an existing good example, or how should one approach creating a basic Template system (thinking MVC) that supports "Template Inheritance" in PHP5? For an example of what I define as Template Inheritance, refer to the Django (a Python framework for web development) Templates documentation: http://docs.djangoproject.com/en/dev/topics/templates/#id1 I especially like the idea of PHP itself being the "template language", though it's not necessarily a requirement. If listing existing solutions that implement "Template Inheritance", please try to form answers as individual systems, for the benefit of 'popular vote'.

    Read the article

  • Instance where embedded C++ compilers don't support multiple inheritance?

    - by Nathan
    I read a bit about a previous attempt to make a C++ standard for embedded platforms where they specifically said multiple inheritance was bad and thus not supported. From what I understand, this was never implemented as a mainstream thing and most embedded C++ compilers support most standard C++ constructs. Are there cases where a compiler on a current embedded platform (i.e. something not more than a few years old) absolutely does not support multiple inheritance? I don't really want to do multiple inheritance in a sense where I have a child with two full implementations of a class. What I am most interested in is inheriting from a single implementation of a class and then also inheriting one or more pure virtual classes as interfaces only. This is roughly equivalent to Java/.Net where I can extend only one class but implement as many interfaces as I need. In C++ this is all done through multiple inheritance rather than being able to specifically define an interface and declare a class implements it.

    Read the article

  • How to return children objects?

    - by keruilin
    I have -- what I think -- is a simple question. Here's my code: class Fruit < ActiveRecord::Base end class Apple < Fruit end class Kiwi < Fruit end Assume that I have all the STI setup correctly, and there are multiple types of Apple and Kiwi records in the table. From here... fruits = Fruit.find(:all) ...how do I return an array of just Apples from the fruits array?

    Read the article

  • Getting functions of inherited functions to be called

    - by wrongusername
    Let's say I have a base class Animal from which a class Cow inherits, and a Barn class containing an Animal vector, and let's say the Animal class has a virtual function scream(), which Cow overrides. With the following code: Animal.h #ifndef _ANIMAL_H #define _ANIMAL_H #include <iostream> using namespace std; class Animal { public: Animal() {}; virtual void scream() {cout << "aaaAAAAAAAAAAGHHHHHHHHHH!!! ahhh..." << endl;} }; #endif /* _ANIMAL_H */ Cow.h #ifndef _COW_H #define _COW_H #include "Animal.h" class Cow: public Animal { public: Cow() {} void scream() {cout << "MOOooooOOOOOOOO!!!" << endl;} }; #endif /* _COW_H */ Barn.h #ifndef _BARN_H #define _BARN_H #include "Animal.h" #include <vector> class Barn { std::vector<Animal> animals; public: Barn() {} void insertAnimal(Animal animal) {animals.push_back(animal);} void tortureAnimals() { for(int a = 0; a < animals.size(); a++) animals[a].scream(); } }; #endif /* _BARN_H */ and finally main.cpp #include <stdlib.h> #include "Barn.h" #include "Cow.h" #include "Chicken.h" /* * */ int main(int argc, char** argv) { Barn barn; barn.insertAnimal(Cow()); barn.tortureAnimals(); return (EXIT_SUCCESS); } I get this output: aaaAAAAAAAAAAGHHHHHHHHHH!!! ahhh... How should I code this to get MOOooooOOOOOOOO!!! (and whatever other classes inheriting Animal wants scream() to be) instead?

    Read the article

  • Rails object inheritence with belongs_to

    - by Rabbott
    I have a simple has_many/belongs_to relationship between Report and Chart. The issue I'm having is that my Chart model is a parent that has children. So in my Report model I have class Report < ActiveRecord::Base has_many :charts end And my Chart model is a parent, where Pie, Line, Bar all inherit from Chart. I'm not sure where the belongs_to :report belongs within the chart model, or children of chart model. I get errors when I attempt to access chart.report because the object is of type "Class" undefined local variable or method `report' for #< Class:0x104974b90 The Chart model uses STI so its pulling say.. 'Pie' from the chart_type column in the charts table.. what am I missing?

    Read the article

  • Inheritance Mapping Strategies with Entity Framework Code First CTP5: Part 2 – Table per Type (TPT)

    - by mortezam
    In the previous blog post you saw that there are three different approaches to representing an inheritance hierarchy and I explained Table per Hierarchy (TPH) as the default mapping strategy in EF Code First. We argued that the disadvantages of TPH may be too serious for our design since it results in denormalized schemas that can become a major burden in the long run. In today’s blog post we are going to learn about Table per Type (TPT) as another inheritance mapping strategy and we'll see that TPT doesn’t expose us to this problem. Table per Type (TPT)Table per Type is about representing inheritance relationships as relational foreign key associations. Every class/subclass that declares persistent properties—including abstract classes—has its own table. The table for subclasses contains columns only for each noninherited property (each property declared by the subclass itself) along with a primary key that is also a foreign key of the base class table. This approach is shown in the following figure: For example, if an instance of the CreditCard subclass is made persistent, the values of properties declared by the BillingDetail base class are persisted to a new row of the BillingDetails table. Only the values of properties declared by the subclass (i.e. CreditCard) are persisted to a new row of the CreditCards table. The two rows are linked together by their shared primary key value. Later, the subclass instance may be retrieved from the database by joining the subclass table with the base class table. TPT Advantages The primary advantage of this strategy is that the SQL schema is normalized. In addition, schema evolution is straightforward (modifying the base class or adding a new subclass is just a matter of modify/add one table). Integrity constraint definition are also straightforward (note how CardType in CreditCards table is now a non-nullable column). Another much more important advantage is the ability to handle polymorphic associations (a polymorphic association is an association to a base class, hence to all classes in the hierarchy with dynamic resolution of the concrete class at runtime). A polymorphic association to a particular subclass may be represented as a foreign key referencing the table of that particular subclass. Implement TPT in EF Code First We can create a TPT mapping simply by placing Table attribute on the subclasses to specify the mapped table name (Table attribute is a new data annotation and has been added to System.ComponentModel.DataAnnotations namespace in CTP5): public abstract class BillingDetail {     public int BillingDetailId { get; set; }     public string Owner { get; set; }     public string Number { get; set; } } [Table("BankAccounts")] public class BankAccount : BillingDetail {     public string BankName { get; set; }     public string Swift { get; set; } } [Table("CreditCards")] public class CreditCard : BillingDetail {     public int CardType { get; set; }     public string ExpiryMonth { get; set; }     public string ExpiryYear { get; set; } } public class InheritanceMappingContext : DbContext {     public DbSet<BillingDetail> BillingDetails { get; set; } } If you prefer fluent API, then you can create a TPT mapping by using ToTable() method: protected override void OnModelCreating(ModelBuilder modelBuilder) {     modelBuilder.Entity<BankAccount>().ToTable("BankAccounts");     modelBuilder.Entity<CreditCard>().ToTable("CreditCards"); } Generated SQL For QueriesLet’s take an example of a simple non-polymorphic query that returns a list of all the BankAccounts: var query = from b in context.BillingDetails.OfType<BankAccount>() select b; Executing this query (by invoking ToList() method) results in the following SQL statements being sent to the database (on the bottom, you can also see the result of executing the generated query in SQL Server Management Studio): Now, let’s take an example of a very simple polymorphic query that requests all the BillingDetails which includes both BankAccount and CreditCard types: projects some properties out of the base class BillingDetail, without querying for anything from any of the subclasses: var query = from b in context.BillingDetails             select new { b.BillingDetailId, b.Number, b.Owner }; -- var query = from b in context.BillingDetails select b; This LINQ query seems even more simple than the previous one but the resulting SQL query is not as simple as you might expect: -- As you can see, EF Code First relies on an INNER JOIN to detect the existence (or absence) of rows in the subclass tables CreditCards and BankAccounts so it can determine the concrete subclass for a particular row of the BillingDetails table. Also the SQL CASE statements that you see in the beginning of the query is just to ensure columns that are irrelevant for a particular row have NULL values in the returning flattened table. (e.g. BankName for a row that represents a CreditCard type) TPT ConsiderationsEven though this mapping strategy is deceptively simple, the experience shows that performance can be unacceptable for complex class hierarchies because queries always require a join across many tables. In addition, this mapping strategy is more difficult to implement by hand— even ad-hoc reporting is more complex. This is an important consideration if you plan to use handwritten SQL in your application (For ad hoc reporting, database views provide a way to offset the complexity of the TPT strategy. A view may be used to transform the table-per-type model into the much simpler table-per-hierarchy model.) SummaryIn this post we learned about Table per Type as the second inheritance mapping in our series. So far, the strategies we’ve discussed require extra consideration with regard to the SQL schema (e.g. in TPT, foreign keys are needed). This situation changes with the Table per Concrete Type (TPC) that we will discuss in the next post. References ADO.NET team blog Java Persistence with Hibernate book a { text-decoration: none; } a:visited { color: Blue; } .title { padding-bottom: 5px; font-family: Segoe UI; font-size: 11pt; font-weight: bold; padding-top: 15px; } .code, .typeName { font-family: consolas; } .typeName { color: #2b91af; } .padTop5 { padding-top: 5px; } .padTop10 { padding-top: 10px; } p.MsoNormal { margin-top: 0in; margin-right: 0in; margin-bottom: 10.0pt; margin-left: 0in; line-height: 115%; font-size: 11.0pt; font-family: "Calibri" , "sans-serif"; }

    Read the article

  • GCC: Simple inheritance test fails

    - by knight666
    I'm building an open source 2D game engine called YoghurtGum. Right now I'm working on the Android port, using the NDK provided by Google. I was going mad because of the errors I was getting in my application, so I made a simple test program: class Base { public: Base() { } virtual ~Base() { } }; // class Base class Vehicle : virtual public Base { public: Vehicle() : Base() { } ~Vehicle() { } }; // class Vehicle class Car : public Vehicle { public: Car() : Base(), Vehicle() { } ~Car() { } }; // class Car int main(int a_Data, char** argv) { Car* stupid = new Car(); return 0; } Seems easy enough, right? Here's how I compile it, which is the same way I compile the rest of my code: /home/oem/android-ndk-r3/build/prebuilt/linux-x86/arm-eabi-4.4.0/bin/arm-eabi-g++ -g -std=c99 -Wall -Werror -O2 -w -shared -fshort-enums -I ../../YoghurtGum/src/GLES -I ../../YoghurtGum/src -I /home/oem/android-ndk-r3/build/platforms/android-5/arch-arm/usr/include -c src/Inheritance.cpp -o intermediate/Inheritance.o (Line breaks are added for clarity). This compiles fine. But then we get to the linker: /home/oem/android-ndk-r3/build/prebuilt/linux-x86/arm-eabi-4.4.0/bin/arm-eabi-gcc -lstdc++ -Wl, --entry=main, -rpath-link=/system/lib, -rpath-link=/home/oem/android-ndk-r3/build/platforms/android-5/arch-arm/usr/lib, -dynamic-linker=/system/bin/linker, -L/home/oem/android-ndk-r3/build/prebuilt/linux-x86/arm-eabi-4.4.0/lib/gcc/arm-eabi/4.4.0, -L/home/oem/android-ndk-r3/build/platforms/android-5/arch-arm/usr/lib, -rpath=../../YoghurtGum/lib/GLES -nostdlib -lm -lc -lGLESv1_CM -z /home/oem/android-ndk-r3/build/platforms/android-5/arch-arm/usr/lib/crtbegin_dynamic.o /home/oem/android-ndk-r3/build/platforms/android-5/arch-arm/usr/lib/crtend_android.o intermediate/Inheritance.o ../../YoghurtGum/bin/YoghurtGum.a -o bin/Galaxians.android As you can probably tell, there's a lot of cruft in there that isn't really needed. That's because it doesn't work. It fails with the following errors: intermediate/Inheritance.o:(.rodata._ZTI3Car[typeinfo for Car]+0x0): undefined reference to `vtable for __cxxabiv1::__si_class_type_info' intermediate/Inheritance.o:(.rodata._ZTI7Vehicle[typeinfo for Vehicle]+0x0): undefined reference to `vtable for __cxxabiv1::__vmi_class_type_info' intermediate/Inheritance.o:(.rodata._ZTI4Base[typeinfo for Base]+0x0): undefined reference to `vtable for __cxxabiv1::__class_type_info' collect2: ld returned 1 exit status make: *** [bin/Galaxians.android] Fout 1 These are the same errors I get from my actual application. If someone could explain to me where I went wrong in my test or what option or I forgot in my linker, I would be very, extremely grateful. Thanks in advance. UPDATE: When I make my destructors non-inlined, I get new and more exciting link errors: intermediate/Inheritance.o:(.rodata+0x78): undefined reference to `vtable for __cxxabiv1::__si_class_type_info' intermediate/Inheritance.o:(.rodata+0x90): undefined reference to `vtable for __cxxabiv1::__vmi_class_type_info' intermediate/Inheritance.o:(.rodata+0xb0): undefined reference to `vtable for __cxxabiv1::__class_type_info' collect2: ld returned 1 exit status make: *** [bin/Galaxians.android] Fout 1

    Read the article

  • How does object of sub-class record information about its super-class the in a Virtual Inheritance

    - by Summer_More_More_Tea
    Hi there: I encounter this problem when tackling with virtual inheritance. I remember that in a non-virtual inheritance hierarchy, object of sub-class hold an object of its direct super-class. What about virtual inheritance? In this situation, does object of sub-class hold an object of its super-class directly or just hold a pointer pointing to an object of its super-class? By the way, why the output of the following code is: sizeof(A): 8 sizeof(B): 20 sizeof(C): 32 Code: #include <iostream> using namespace std; class A{ char k[ 3 ]; public: virtual void a(){}; }; class B : public virtual A{ char j[ 3 ]; public: virtual void b(){}; }; class C : public virtual B{ char i[ 3 ]; public: virtual void c(){}; }; int main( int argc, char *argv[] ){ cout << "sizeof(A): " << sizeof( A ) << endl; cout << "sizeof(B): " << sizeof( B ) << endl; cout << "sizeof(C): " << sizeof( C ) << endl; return 0; } Thanks in advance. Kind regards.

    Read the article

  • Multiple Inheritance Debates II: according to Stroutroup

    - by asksuperuser
    I know very well about the traditional arguments about why Interface Inheritance is prefered to multiple inheritance, there has been already a post here : http://stackoverflow.com/questions/191691/should-c-include-multiple-inheritance But according to Stroutroup the real reason why Microsoft and Sun decided to get rid off multiple inheritance is that they have vested interest to do so: instead of putting features in the languages, they put in frameworks so that people then become tied to their platform instead of people having the same capability at a language standard level. What do you think ?

    Read the article

  • Abstract class + Inheritance vs Interface

    - by RealityDysfunction
    Hello fellow programmers, I am reading a book on C# and the author is comparing Abstract classes and Interfaces. He claims that if you have the following "abstract class:" abstract class CloneableType { public abstract object Clone(); } Then you cannot do this: public class MiniVan : Car, CloneableType {} This, I understand. However he claims that because of this inability to do multiple inheritance that you should use an interface for CloneableType, like so: public interface ICloneable { object Clone(); } My question is, isn't this somewhat misleading, because you can create an abstract class which is "above" class Car with the method Clone, then have Car inherit that class and then Minivan will inherit Car with all these methods, CloneAble class - Car class - Minivan Class. What do you think? Thanks.

    Read the article

  • Visitor-pattern vs inheritance for rendering

    - by akaltar
    I have a game engine that currently uses inheritance to provide a generic interface to do rendering: class renderable { public: void render(); }; Each class calls the gl_* functions itself, this makes the code hard to optimize and hard to implement something like setting the quality of rendering: class sphere : public renderable { public: void render() { glDrawElements(...); } }; I was thinking about implementing a system where I would create a Renderer class that would render my objects: class sphere { void render( renderer* r ) { r->renderme( *this ); } }; class renderer { renderme( sphere& sphere ) { // magically get render resources here // magically render a sphere here } }; My main problem is where should I store the VBOs and where should I Create them when using this method? Should I even use this approach or stick to the current one, perhaps something else? PS: I already asked this question on SO but got no proper answers.

    Read the article

  • Inheritance of list-style-type property in Firefox (bug in Firebug?)

    - by Marcel Korpel
    Let's have a look at some comments on a page generated by Wordpress (it's not a site I maintain, I'm just wondering what's going on here). As these pages might disappear in the near future, I've put some screenshots online. Here's what I saw: Obviously, the list-item markers shouldn't be there. So I decided to look at the source using Firebug. As you can see, Firebug claims that the list-style property (containing none) is inherited from ol.commentlist. But if that's the case, why are the circle and the square visible? When checking the computed style, Firebug shows the list-style-types correctly. What's the correct behaviour? I just did a quick check in Chromium, whose Web Inspector gave a better view of reality (the list item markers were also displayed in this browser): According to WebKit, list-style of ol.commentlist isn't inherited, only the default value of list-style-type from the rendering engine. So, we may conclude that the output of both browsers is correct and that Firefox (Firebug) shows an incorrect representation of inherited styles. What does the CSS specification say? Inheritance will transfer the list-style values from OL and UL elements to LI elements. This is the recommended way to specify list style information. Not much about the inheritance of ol properties to uls. Is Firebug wrong in this respect? BTW, I managed to let the markers disappear by just changing line 312 of style.css to ol.commentlist, li.commentlist, ul.children { When also explicitly defining the list-style of ul.children to none, the markers are not painted. You can have a look at screenshots of Firebug and WebKit's Web Inspector in this case, if you like.

    Read the article

  • Inheritance, commands and event sourcing

    - by Arthis
    In order not to redo things several times I wanted to factorize common stuff. For Instance, let's say we have a cow and a horse. The cow produces milk, the horse runs fast, but both eat grass. public class Herbivorous { public void EatGrass(int quantity) { var evt= Build.GrassEaten .WithQuantity(quantity); RaiseEvent(evt); } } public class Horse : Herbivorous { public void RunFast() { var evt= Build.FastRun; RaiseEvent(evt); } } public class Cow: Herbivorous { public void ProduceMilk() { var evt= Build.MilkProduced; RaiseEvent(evt); } } To eat Grass, the command handler should be : public class EatGrassHandler : CommandHandler<EatGrass> { public override CommandValidation Execute(EatGrass cmd) { Contract.Requires<ArgumentNullException>(cmd != null); var herbivorous= EventRepository.GetById<Herbivorous>(cmd.Id); if (herbivorous.IsNull()) throw new AggregateRootInstanceNotFoundException(); herbivorous.EatGrass(cmd.Quantity); EventRepository.Save(herbivorous, cmd.CommitId); } } so far so good. I get a Herbivorous object , I have access to its EatGrass function, whether it is a horse or a cow doesn't matter really. The only problem is here : EventRepository.GetById<Herbivorous>(cmd.Id) Indeed, let's imagine we have a cow that has produced milk during the morning and now wants to eat grass. The EventRepository contains an event MilkProduced, and then come the command EatGrass. With the CommandHandler, we are no longer in the presence of a cow and the herbivorious doesn't know anything about producing milk . what should it do? Ignore the event and continue , thus allowing the inheritance and "general" commands? or throw an exception to forbid execution, it would mean only CowEatGrass, and HorseEatGrass might exists as commands ? Thanks for your help, I am just beginning with these kinds of problem, and I would be glad to have some news from someone more experienced.

    Read the article

  • Code contracts and inheritance

    - by DigiMortal
    In my last posting about code contracts I introduced you how to force code contracts to classes through interfaces. In this posting I will go step further and I will show you how code contracts work in the case of inherited classes. As a first thing let’s take a look at my interface and code contracts. [ContractClass(typeof(ProductContracts))] public interface IProduct {     int Id { get; set; }     string Name { get; set; }     decimal Weight { get; set; }     decimal Price { get; set; } }   [ContractClassFor(typeof(IProduct))] internal sealed class ProductContracts : IProduct {     private ProductContracts() { }       int IProduct.Id     {         get         {             return default(int);         }         set         {             Contract.Requires(value > 0);         }     }       string IProduct.Name     {         get         {             return default(string);         }         set         {             Contract.Requires(!string.IsNullOrWhiteSpace(value));             Contract.Requires(value.Length <= 25);         }     }       decimal IProduct.Weight     {         get         {             return default(decimal);         }         set         {             Contract.Requires(value > 3);             Contract.Requires(value < 100);         }     }       decimal IProduct.Price     {         get         {             return default(decimal);         }         set         {             Contract.Requires(value > 0);             Contract.Requires(value < 100);         }     } } And here is the product class that inherits IProduct interface. public class Product : IProduct {     public int Id { get; set; }     public string Name { get; set; }     public virtual decimal Weight { get; set; }     public decimal Price { get; set; } } if we run this code and violate the code contract set to Id we will get ContractException. public class Program {     static void Main(string[] args)     {         var product = new Product();         product.Id = -100;     } }   Now let’s make Product to be abstract class and let’s define new class called Food that adds one more contract to Weight property. public class Food : Product {     public override decimal Weight     {         get         {             return base.Weight;         }         set         {             Contract.Requires(value > 1);             Contract.Requires(value < 10);               base.Weight = value;         }     } } Now we should have the following rules at place for Food: weight must be greater than 1, weight must be greater than 3, weight must be less than 100, weight must be less than 10. Interesting part is what happens when we try to violate the lower and upper limits of Food weight. To see what happens let’s try to violate rules #2 and #4. Just comment one of the last lines out in the following method to test another assignment. public class Program {     static void Main(string[] args)     {         var food = new Food();         food.Weight = 12;         food.Weight = 2;     } } And here are the results as pictures to see where exceptions are thrown. Click on images to see them at original size. Violation of lower limit. Violation of upper limit. As you can see for both violations we get ContractException like expected. Code contracts inheritance is powerful and at same time dangerous feature. Although you can always narrow down the conditions that come from more general classes it is possible to define impossible or conflicting contracts at different points in inheritance hierarchy.

    Read the article

  • Inheritance vs containment while extending a large legacy project

    - by Flot2011
    I have got a legacy Java project with a lot of code. The code uses MVC pattern and is well structured and well written. It also has a lot of unit tests and it is still actively maintained (bug fixing, minor features adding). Therefore I want to preserve the original structure and code style as much as possible. The new feature I am going to add is a conceptual one, so I have to make my changes all over the code. In order to minimize changes I decided not to extend existing classes but to use containment: class ExistingClass { // .... existing code // my code adding new functionality private ExistingClassExtension extension = new ExistingClassExtension(); public ExistingClassExtension getExtension() {return extension;} } ... // somewhere in code ExistingClass instance = new ExistingClass(); ... // when I need a new functionality instance.getExtension().newMethod1(); All functionality that I am adding is inside a new ExistingClassExtension class. Actually I am adding only these 2 lines to each class that needs to be extended. By doing so I also do not need to instantiate new, extended classes all over the code and I may use existing tests to make sure there is no regression. However my colleagues argue that in this situation doing so isn't a proper OOP approach, and I need to inherit from ExistingClass in order to add a new functionality. What do you think? I am aware of numerous inheritance/containment questions here, but I think my question is different.

    Read the article

  • Modeling a cellphone bill: should I use single-table inheritance or polymorphic associations?

    - by Horace Loeb
    In my domain: Users have many Bills Bills have many BillItems (and therefore Users have many BillItems through Bills) Every BillItem is one of: Call SMS (text message) MMS (multimedia message) Data Here are the properties of each individual BillItem (some are common): My question is whether I should model this arrangement with single-table inheritance (i.e., one "bill_items" table with a "type" column) or polymorphism (separate tables for each BillItem type), and why.

    Read the article

  • Who calls the Destructor of the class when operator delete is used in multiple inheritance.

    - by dicaprio-leonard
    This question may sound too silly, however , I don't find concrete answer any where else. With little knowledge on how late binding works and virtual keyword used in inheritance. As in the code sample, when in case of inheritance where a base class pointer pointing to a derived class object created on heap and delete operator is used to deallocate the memory , the destructor of the of the derived and base will be called in order only when the base destructor is declared virtual function. Now my question is : 1) When the destructor of base is not virtual, why the problem of not calling derived dtor occur only when in case of using "delete" operator , why not in the case given below: derived drvd; base *bPtr; bPtr = &drvd; //DTOR called in proper order when goes out of scope. 2) When "delete" operator is used, who is reponsible to call the destructor of the class? The operator delete will have an implementation to call the DTOR ? or complier writes some extra stuff ? If the operator has the implementation then how does it looks like , [I need sample code how this would have been implemented]. 3) If virtual keyword is used in this example, how does operator delete now know which DTOR to call? Fundamentaly i want to know who calls the dtor of the class when delete is used. Sample Code class base { public: base() { cout<<"Base CTOR called"<<endl; } virtual ~base() { cout<<"Base DTOR called"<<endl; } }; class derived:public base { public: derived() { cout<<"Derived CTOR called"<<endl; } ~derived() { cout<<"Derived DTOR called"<<endl; } }; I'm not sure if this is a duplicate, I couldn't find in search. int main() { base *bPtr = new derived(); delete bPtr;// only when you explicitly try to delete an object return 0; }

    Read the article

< Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >