  We construct cubic gravity and its $f(P)$ extension and we investigate their
early- and late-time cosmological applications. Cubic gravity is based on a
particular invariant $P$, constructed from cubic contractions of the Riemann
tensor, under three requirements: (i) the resulting theory possesses a spectrum
identical to that of general relativity, (ii) it is neither topological nor
trivial in four dimensions, and (iii) it is defined such that it is independent
of the dimensions. Relaxing the last condition and restricting the parameters
of cubic gravity we can obtain second-order field equations in a cosmological
background. We show that at early times one can obtain inflationary, de Sitter
solutions, which are driven by an effective cosmological constant constructed
purely from the cubic terms of the simple cubic or $f(P)$ gravity. Concerning
late-time evolution, the new terms constitute an effective dark-energy sector
and we show that the Universe experiences the usual thermal history and the
onset of late-time acceleration. In the case of $f(P)$ gravity, depending on
the choice of parameters, we find that the dark-energy equation-of-state
parameter can be quintessencelike, phantomlike or it can experience the
phantom-divide crossing during the evolution, even if an explicit cosmological
constant is absent.
