I want to create an interface that implements some of its own methods in Java (but the language won’t allow this, as shown below):
//Java-style pseudo-code
public interface Square {
//Implement a method in the interface itself
public int getSize(){//this can't be done in Java; can it be done in C++?
//inherited by every class that implements getWidth()
//and getHeight()
return getWidth()*getHeight();
}
public int getHeight();
public int getWidth();
}
//again, this is Java-style psuedocode
public class Square1 implements Square{
//getSize should return this.getWidth()*this.getHeight(), as implemented below
public int getHeight(){
//method body goes here
}
public int getWidth{
//method body goes here
}
}
Is it possible to create the equivalent of an interface in C++ that can implement some of its own methods?
To answer your other question, yes it can be done in C++ through the use of the
virtualkeyword. To my knowledge, it is the primary method of polymorphism in C++.This set of tutorials is great; I would recommend a solid read-through if you want to learn more about C/C++.