Jump to content

Sealed classes and methods: Difference between revisions

C++ entry
m (→‎{{header|C}}: Added return value.)
(C++ entry)
Line 68:
Lisa is watching the movie...
Sorry, Fred, you are too young to watch the movie.
</pre>
 
=={{header|C++}}==
Classes and functions can be sealed in C++ by using the '''final''' keyword.
<syntaxhighlight lang="cpp">#include <iostream>
#include <memory>
#include <string>
#include <vector>
 
class MovieWatcher // A base class for movie watchers
{
protected:
std::string m_name;
 
public:
explicit MovieWatcher(std::string_view name) : m_name{name}{}
virtual void WatchMovie() = 0; // must be overridden by derived classes
virtual void EatPopcorn()
{
std::cout << m_name << " is enjoying the popcorn\n";
}
virtual ~MovieWatcher() = default;
};
 
// ParentMovieWatcher cannot be inherited from because it is 'final'
class ParentMovieWatcher final : public MovieWatcher
{
public:
explicit ParentMovieWatcher(std::string_view name) : MovieWatcher{name} {}
void WatchMovie() override
{
std::cout << m_name << " is watching the movie...\n";
}
};
 
// ChildMovieWatcher can be inherited from
class ChildMovieWatcher : public MovieWatcher
{
int m_age;
public:
ChildMovieWatcher(std::string_view name, int age)
: MovieWatcher{name}, m_age{age}{}
// WatchMovie() cannot be overridden because it is 'final'
void WatchMovie() final override
{
if (m_age < 15)
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";
}
};
 
int main()
{
std::vector<std::unique_ptr<MovieWatcher>> movieWatchers;
movieWatchers.emplace_back(new ParentMovieWatcher("Donald"));
movieWatchers.emplace_back(new ChildMovieWatcher("Lisa", 18));
movieWatchers.emplace_back(new ChildMovieWatcher("Fred", 10));
 
// Send them to the movies
std::for_each(movieWatchers.begin(), movieWatchers.end(), [](auto& watcher)
{
watcher->WatchMovie();
});
std::for_each(movieWatchers.begin(), movieWatchers.end(), [](auto& watcher)
{
watcher->EatPopcorn();
});
}
</syntaxhighlight>
{{out}}
<pre>
Donald is watching the movie...
Lisa likes 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 popcorn in the lobby
</pre>
 
125

edits

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