Jump to content

Sealed classes and methods: Difference between revisions

Update C++ entry
(Removed mention of private methods in description)
(Update C++ entry)
Line 84:
public:
explicit MovieWatcher(std::string_view name) : m_name{name}{}
virtual void WatchMovie() = 0; // must be overridden by derived classes
virtual void WatchMovie() override
{
std::cout << m_name << " likesis watching the movie\n";
}
virtual void EatPopcorn()
{
Line 97 ⟶ 102:
public:
explicit ParentMovieWatcher(std::string_view name) : MovieWatcher{name} {}
};
 
// ChildMovieWatcher can be inherited from
class ChildMovieWatcher : public MovieWatcher
{
public:
explicit ChildMovieWatcher(std::string_view name)
: MovieWatcher{name}{}
// EatPopcorn() cannot be overridden because it is 'final'
void WatchMovie() override
void EatPopcorn() final override
{
std::cout << m_name << " is watchingeating thetoo movie...much popcorn\n";
}
};
 
class YoungChildMovieWatcher : public ChildMovieWatcher
// ChildMovieWatcher can be inherited from
class ChildMovieWatcher : public MovieWatcher
{
int m_age;
public:
ChildMovieWatcherexplicit YoungChildMovieWatcher(std::string_view name, int age)
: MovieWatcherChildMovieWatcher{name}, m_age{age}{}
// WatchMovie() cannot be overridden because it is 'final'
void WatchMovie() final override
{
ifstd::cout (m_age<< "Sorry, " << 15)m_name <<
std::cout << "Sorry, " << m_name <<
", you are too young to watch the movie.\n";
else
std::cout << m_name << " likes the movie\n";
}
void EatPopcorn() override
{
if (m_age < 15)
std::cout << m_name << " is eating popcorn in the lobby\n";
else
std::cout << m_name << " is eating too much popcorn\n";
}
};
Line 133 ⟶ 134:
int main()
{
// A container for the MovieWatcher base class objects
std::vector<std::unique_ptr<MovieWatcher>> movieWatchers;
// Add some movie wathcers
movieWatchers.emplace_back(new ParentMovieWatcher("Donald"));
movieWatchers.emplace_back(new ChildMovieWatcher("Lisa", 18));
movieWatchers.emplace_back(new ChildMovieWatcherYoungChildMovieWatcher("Fred", 10));
 
// Send them to the movies
Line 151 ⟶ 155:
{{out}}
<pre>
Donald is watching the movie...
Lisa likesis watching the movie
Sorry, Fred, you are too young to watch the movie.
Donald is enjoying the popcorn
Lisa is eating too much popcorn
Fred is eating popcorntoo inmuch the lobbypopcorn
</pre>
 
125

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.