简体   繁体   中英

Java Interface in C++

first posting so please be gentle!

I have an interface that's like this

public interface I_Hospital{
    public void registerObserver(I_Person p);
    public void removeObserver(I_Person p);
    public void notifyObservers();
    public void addWard(Ward ward);
}

Now, if I want to recreate this in C++, is it correct to do the following:

IHospital.h

Class IHospital{
    public:
    virtual void registerObserver(IPerson p) = 0;
    etc...
}

Is this the correct implementation on an Interface in C++??

Thanks, Patrick

Yes, you'd define an interface as an abstract class containing pure virtual functions (with the purity indicated by = 0 ), just like that. Like Java's interfaces, abstract classes can't be instantiated directly, but must be derived from by concrete classes which override and implement the pure virtual functions.

There are a couple of issues:

  • the keyword to introduce a class is class not Class
  • you'll want to take the IPerson parameter by reference, IPerson & , not by value; abstract classes can't be passed by value. The same probably applies to the Ward argument; even if it's not abstract, you probably want this class to refer to a ward (as the Java version would), not copy one. Unlike Java, passing a class object to a function will pass a copy of the object, unless you specifically request that it's passed by reference.

A Java interface provides methods that must be overridden by classes that inherit from that interface. This is akin to having an abstract C++ base class that pure virtual methods, like the one you've shown. So yes, that is the correct implementation. Also note that in base classes should have virtual destructors so that deleting a base class pointer to a derived instance correctly calls the derived and base class destructors.

Yes, this is as close as you can get to Java's concept of interfaces.

Note that C++ doesn't actually have a concept of an interface as a separate thing from a class. However, it is customary for C++ developers to refer to classes that have no data members and whose methods are all pure virtual as interfaces -- this is a distinction made by programmers, not the language itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM