Unit 3: Data Files, Constructors and Destructors - Practice Quiz

CSE202 — Object Oriented Programming 60 Questions
0 Correct 0 Wrong 60 Left
0/60

1 Which member function opens a file for an existing C++ file stream object?

Opening and closing files Easy
A. write()
B. open()
C. close()
D. read()

2 Which member function should be used to disconnect a file from a file stream?

Opening and closing files Easy
A. clear()
B. flush()
C. ignore()
D. close()

3 Which C++ file mode opens a file for appending data at the end?

File modes Easy
A. ios::out
B. ios::in
C. ios::trunc
D. ios::app

4 Which C++ file mode is primarily used to open a file for reading?

File modes Easy
A. ios::in
B. ios::ate
C. ios::app
D. ios::out

5 Which file stream function returns the current position of the input pointer?

File stream functions Easy
A. tellg()
B. tellp()
C. seekp()
D. seekg()

6 Which operator is commonly used to write formatted data to an ofstream object?

Reading and writing files Easy
A. <<
B. &&
C. ==
D. >>

7 Which function reads an entire line of text from a file stream?

Reading and writing files Easy
A. getline()
B. write()
C. get()
D. put()

8 In sequential file access, how are records normally processed?

Sequential access and random access file processing Easy
A. By random position
B. In stored order
C. In reverse order
D. By memory address

9 Which function moves the input pointer to a specified location in a file?

Sequential access and random access file processing Easy
A. tellg()
B. seekg()
C. seekp()
D. eof()

10 Which mode flag opens a file for binary operations in C++?

Binary file operations Easy
A. ios::binary
B. ios::text
C. ios::format
D. ios::input

11 Which member function writes a block of binary data to a file stream?

Binary file operations Easy
A. read()
B. write()
C. getline()
D. ignore()

12 Which stream class can both read from and write to files?

Classes and file operations Easy
A. ifstream
B. fstream
C. ofstream
D. istream

13 Which C++ keyword is used to define a structure whose records may be stored in a file?

Structures and file operations Easy
A. struct
B. class
C. union
D. enum

14 When is a constructor normally called for an object?

Manager functions: constructors and destructor Easy
A. When the program is compiled
B. When the object is destroyed
C. When the object is created
D. When the file is closed

15 What is a default constructor?

Default constructor Easy
A. A function that destroys objects
B. A function that copies files
C. A constructor callable without arguments
D. A constructor requiring one argument

16 What does a default argument in a constructor provide?

Constructor with default arguments Easy
A. A mode used for file access
B. A name used for the class
C. A value used after destruction
D. A value used when omitted

17 Which symbol appears before the class name in a destructor declaration?

Destructors Easy
A. Hash #
B. Colon :
C. Tilde ~
D. Ampersand &

18 What distinguishes a parameterized constructor from a default constructor?

Parameterized constructor Easy
A. It accepts one or more parameters
B. It returns one or more values
C. It destroys one or more objects
D. It closes one or more files

19 What is the main purpose of a copy constructor?

Copy constructor Easy
A. To append an object to a file
B. To delete an object from memory
C. To initialize an object from another
D. To move a file pointer backward

20 Which symbol introduces a constructor initializer list in C++?

Initializer lists Easy
A. Semicolon ;
B. Comma ,
C. Period .
D. Colon :

21 A program has finished using an input file but will continue running for a long time. Which statement releases the file resource immediately and safely?

Opening and closing files Medium
A. in.flush(); closes the input file after transferring all buffered input to the program.
B. if (in.is_open()) in.close();
C. if (in.good()) in.open();
D. if (in.eof()) in.clear();

22 Which mode should be used with an ofstream to preserve existing content and force every new write to the end of the file?

File modes Medium
A. ios::out | ios::trunc
B. ios::in | ios::out
C. ios::out | ios::app
D. ios::out | ios::ate

23 An input stream has read part of a binary file. Which pair of functions can obtain the current input position and then move it back to the beginning?

File stream functions Medium
A. tellg() and seekg(0, ios::beg)
B. tellp() and seekp(0, ios::beg)
C. eof() and clear() because clearing the status flags also returns the input pointer to the start.
D. get() and putback(0)

24 After fin >> age;, the statement getline(fin, name); reads an empty string because a newline remains in the stream. Which replacement correctly reads the next nonblank line?

Reading and writing files Medium
A. fin << name;
B. getline(fin, age);
C. fin.get(name);
D. getline(fin >> ws, name);

25 A file contains 1,000 fixed-size records, and the program frequently needs record 700 without processing earlier records. Which approach is most appropriate?

Sequential access and random access file processing Medium
A. Use seekg() with the record's byte offset.
B. Use getline() until record 700 is reached.
C. Close and reopen the file before each record.
D. Read records sequentially from the beginning.

26 Given int value = 25; and an open binary ofstream out, which statement writes the object's raw bytes?

Binary file operations Medium
A. out.write(value, sizeof(char));
B. out.write(reinterpret_cast<const char*>(&value), sizeof(value));
C. out << reinterpret_cast<const char*>(&value);
D. out.put(static_cast<char*>(value));

27 A Student class has private data, but objects must support syntax such as fin >> student. Which declaration best provides this operation while retaining private data?

Classes and file operations Medium
A. istream& operator>>(istream& in);
B. friend Student operator>>(Student s, istream in);
C. friend istream& operator>>(istream& in, Student& s);
D. Make every data member public and let the stream access and modify each field without an extraction operator.

28 A binary file stores raw Record structures. Which loop processes only structures that were read successfully?

Structures and file operations Medium
A. while (in.read(reinterpret_cast<char*>(&r), sizeof(r))) process(r);
B. do { process(r); } while (in.read(reinterpret_cast<char*>(&r), sizeof(r)));
C. while (!in.eof()) { in.read(reinterpret_cast<char*>(&r), sizeof(r)); process(r); }
D. while (in.good()) { process(r); in.read(reinterpret_cast<char*>(&r), sizeof(r)); }

29 When an object of a derived class is created, which order is used for initialization?

Manager functions: constructors and destructor Medium
A. Members in initializer-list order, constructor body, base constructor
B. Base constructor, constructor body, members in reverse declaration order
C. Base constructor, members in declaration order, constructor body
D. Constructor body, base constructor, members in declaration order

30 Consider class Box { public: Box(int size = 1); };. What happens when Box b; is declared?

Default constructor Medium
A. The compiler generates another constructor and ignores the declared constructor because only a constructor with no parameters can perform default initialization.
B. The object is created without calling a constructor.
C. Compilation fails because the constructor has a parameter.
D. The constructor is called with size equal to 1.

31 What is the result of declaring both Item() and Item(int quantity = 1) and then writing Item x;?

Constructor with default arguments Medium
A. Both constructors run in declaration order.
B. The declaration is ambiguous.
C. Item() is always selected.
D. Item(int) is always selected.

32 A Derived object is allocated dynamically and stored in a Base*. What must Base provide so that delete ptr; correctly invokes both destructors?

Destructors Medium
A. A static destructor
B. A protected constructor
C. A destructor that explicitly identifies and calls every possible derived-class destructor before releasing the base portion
D. A virtual destructor

33 Given class Meter { public: explicit Meter(int value); };, which object declaration is valid?

Parameterized constructor Medium
A. Meter m(5);
B. Meter m = 5;
C. Meter m;
D. Meter m = { };

34 A class owns a dynamically allocated array through a pointer member. What should its copy constructor generally do to avoid two objects deleting the same array?

Copy constructor Medium
A. Copy only the pointer address.
B. Allocate a new array and copy its elements.
C. Set both pointers to nullptr.
D. Transfer the pointer from the source object and modify the supposedly constant source so that it no longer owns the allocation.

35 Why must the members in class Entry { const int id; int& value; /* ... */ }; be initialized using a constructor initializer list?

Initializer lists Medium
A. Initializer lists automatically make all members public.
B. Assignments in the constructor body would recreate both members as static variables with program-wide lifetime.
C. Both members must be initialized before the constructor body.
D. The constructor body runs before member initialization.

36 What is the effect of opening an existing file using ofstream out("report.txt", ios::out | ios::trunc);?

File modes Medium
A. The file pointer starts at the end while all existing content remains available for later random-access updates.
B. Its existing contents are discarded.
C. The file becomes read-only.
D. New content is appended to its end.

37 An input stream has reached end-of-file. The program now needs to reread from the beginning. Which sequence is appropriate?

File stream functions Medium
A. in.seekg(0, ios::beg); in.close();
B. in.flush(); in.tellg();
C. in.eof(); in.open();
D. in.clear(); in.seekg(0, ios::beg);

38 A binary file contains fixed-size Record objects indexed from zero. Which statement positions an output stream at record index for an update?

Sequential access and random access file processing Medium
A. file.seekg(k + sizeof(Record), ios::beg);
B. file.seekp(k * sizeof(Record), ios::beg);
C. file.seekp(k, ios::end);
D. file.tellp(k * sizeof(Record));

39 What is the main purpose of including ios::binary when opening a file?

Binary file operations Medium
A. It prevents text-mode byte translations.
B. It automatically compresses file contents.
C. It converts every value into machine code.
D. It makes raw representations portable across all processors, compilers, operating systems, and class versions without additional serialization logic.

40 For Widget items[3];, in what order are the destructors called when the array leaves scope?

Destructors Medium
A. Only items[0] is destroyed automatically.
B. items[1], items[2], items[0]
C. items[2], items[1], items[0]
D. items[0], items[1], items[2]

41 Assume A.bin and B.bin initially exist and are empty. What happens in the following C++ code? std::ofstream f("A.bin", std::ios::binary); f.open("B.bin", std::ios::binary); bool failed = f.fail(); f.clear(); f << "X"; f.close();

Opening and closing files Hard
A. failed is false; A.bin contains X, while B.bin remains empty.
B. failed is true; B.bin contains X, while A.bin remains empty.
C. failed is true; A.bin contains X, while B.bin remains empty.
D. failed is false; both files contain X after f.close().

42 An existing file data.bin contains 10 bytes. What is its size after executing std::ofstream out("data.bin", std::ios::binary | std::ios::ate); out.write("XY", 2); out.close();?

File modes Hard
A. 10 bytes, because the first two bytes are overwritten after opening at the end.
B. 12 bytes, because binary implicitly adds app when combined with ate.
C. 12 bytes, because ate preserves the file and every write is forced to its end.
D. 2 bytes, because ofstream adds out, which truncates the file before the initial end seek.

43 A file contains only 7. Consider int x = 0, y = 99; std::ifstream in("n.txt"); in >> x; in >> y; in.seekg(0); in >> y;. Which statement is correct?

File stream functions Hard
A. y remains 99 because the failed extraction leaves failbit set, preventing the seek and later extraction.
B. y remains 99 because reaching EOF permanently closes the stream's underlying file buffer.
C. y becomes 7 because seekg(0) automatically clears both failbit and eofbit.
D. y becomes 0 because the failed extraction value-initializes the destination before seeking.

44 A text file contains 10 20x 30. What are the final values after int a=-1, b=-1, c=-1; in >> a >> b >> c; in.clear(); in.ignore(1); in >> c;?

Reading and writing files Hard
A. a = 10, b = 20, and c = 30
B. a = 10, b = 20, and c = 0
C. a = 10, b = -1, and c = 30
D. a = 10, b = 20, and c = -1

45 A binary file has a header of bytes followed by fixed-size records of bytes. Which expression gives the starting offset of the record with zero-based index ?

Sequential access and random access file processing Hard
A. static_cast<std::streamoff>(H) + static_cast<std::streamoff>(k) * S
B. static_cast<std::streamoff>(H - 1) + static_cast<std::streamoff>(k) * S
C. static_cast<std::streamoff>(H) * static_cast<std::streamoff>(k + S)
D. static_cast<std::streamoff>(H) + static_cast<std::streamoff>(k + 1) * S

46 Why is writing an object containing std::string name; using out.write(reinterpret_cast<const char*>(&obj), sizeof obj) unsuitable for later reconstruction?

Binary file operations Hard
A. It stores the string object's internal representation rather than the dynamically allocated character sequence.
B. It writes only public data members because private members are inaccessible to ostream::write.
C. It stores characters correctly but omits the null terminator required by std::string reconstruction.
D. It converts the characters to implementation-defined binary codes that formatted input cannot decode.

47 A class has private fields, validates all constructor arguments, and must be loaded from a portable binary file. Which design best preserves its invariants?

Classes and file operations Hard
A. Use a member or friend loader that reads fixed-format fields and invokes a validating constructor.
B. Allocate uninitialized storage, copy the file bytes into it, and treat the storage as a live object.
C. Read sizeof(Class) bytes directly into an object created with its ordinary default constructor.
D. Make every field public temporarily, read raw bytes, and restore access control after loading.

48 A trivially copyable structure contains std::uint32_t id; char flag;. Why can raw write() and read() of the complete structure still fail as a portable file format?

Structures and file operations Hard
A. Trivially copyable structures may be written only through formatted stream insertion operators.
B. Binary streams automatically compress padding bytes and therefore change the structure's size.
C. A structure's member declaration order may be rearranged independently each time it is written.
D. Padding, alignment, byte order, and type representation may differ between implementations.

49 Class D derives from B and declares members M m1; M m2; in that order. Which lifecycle order is guaranteed for a complete D object?

Manager functions: constructors and destructor Hard
A. B, m2, m1, D, then ~D, ~m1, ~m2, ~B
B. D, B, m1, m2, then ~m2, ~m1, ~B, ~D
C. m1, m2, B, D, then ~D, ~B, ~m2, ~m1
D. B, m1, m2, D, then ~D, ~m2, ~m1, ~B

50 Given struct A { A(int value); };, which statement about A a; is correct?

Default constructor Hard
A. It value-initializes the object because every single-parameter constructor also acts as a default constructor.
B. It is well-formed only when A(int) is not marked explicit in the class definition.
C. It calls an implicitly generated A() and then assigns zero to the unnamed constructor parameter.
D. It is ill-formed because declaring A(int) suppresses generation of an implicit default constructor.

51 What is the result of struct C { C(); C(int x = 0); }; C value;?

Constructor with default arguments Hard
A. Compilation fails because both constructors are viable for a call with no arguments.
B. The declaration calls C(int) because its default argument supplies a better conversion sequence.
C. The declaration calls C() because a zero-parameter constructor always has higher priority.
D. Compilation succeeds, but the selected constructor is implementation-defined.

52 Given struct Base { ~Base() {} }; struct Derived : Base { ~Derived() {} };, what is the effect of Base* p = new Derived; delete p;?

Destructors Hard
A. The behavior is undefined because Base lacks a virtual destructor.
B. The program is well-defined only if Derived contains no non-static data members.
C. Both destructors run because the allocated object's dynamic type is Derived.
D. Only Base::~Base() runs, and the behavior is otherwise well-defined.

53 For struct P { explicit P(int); }; void consume(P);, which pair of statements is well-formed?

Parameterized constructor Hard
A. P a = 3; and consume(3);
B. P a = {3}; and consume({3});
C. P a(3); and P b{3};
D. P a; and consume(P());

54 A class Buffer owns memory through int* data, deletes it in its destructor, and defines no copy operations. What is the main risk of Buffer second = first;?

Copy constructor Hard
A. The generated copy constructor copies the pointer, so both objects may delete the same allocation.
B. The pointer is transferred to second, leaving first in an automatically empty state.
C. The copy is rejected because classes containing raw pointers are never implicitly copyable.
D. The generated copy constructor allocates new storage but leaves its elements uninitialized.

55 Under C++17, consider struct C { int y; int x; C() : x(5), y(x + 1) {} };. What is the key issue?

Initializer lists Hard
A. y is initialized before x, so evaluating x + 1 reads an indeterminate value.
B. y is default-initialized and then assigned after x, so both members are valid.
C. The compiler must reorder the member declarations to match the initializer-list order.
D. x is initialized first because it appears first in the initializer list, so y becomes 6.

56 An existing file contains ABCDE. What does std::fstream f("x.txt", std::ios::in | std::ios::out | std::ios::app); f.seekp(0); f << "Z"; produce after the stream is closed?

File modes Hard
A. ZBCDE, because seekp(0) overrides the initial append position.
B. ABCDEZ, because app forces each output operation to the end.
C. ZABCDE, because app inserts output at the requested position.
D. ABCDE, because combining in, out, and app disables output.

57 A binary std::fstream io is open with in | out. After writing a value, which sequence most robustly prepares the stream to read that value from the beginning?

Reading and writing files Hard
A. io.clear(); io.read(buffer, size); io.seekg(0, std::ios::beg);
B. io.flush(); io.seekg(0, std::ios::beg); io.read(buffer, size);
C. io.seekp(0, std::ios::beg); io.read(buffer, size); io.flush();
D. io.read(buffer, size); io.clear(); io.seekp(0, std::ios::end);

58 A file contains fixed-size records of S bytes with no header. To read, modify, and overwrite record i without changing file size, which operation sequence is correct?

Sequential access and random access file processing Hard
A. Seek both positions to (i+1)*S, read the record, and write it at the same position.
B. Seek the put position to i*S, read, then seek the get position to i*S and write.
C. Seek the get position to i*S, read, then seek the put position to i*S and write.
D. Read sequentially through record i, modify it, and write immediately without repositioning.

59 A binary file contains two complete records plus half of a third record. What happens with while (in.read(reinterpret_cast<char*>(&r), sizeof r)) { ++count; } when count initially equals zero?

Binary file operations Hard
A. count becomes 2; the partial read fails, and gcount() reports half a record.
B. count becomes 3; the loop body runs whenever at least one byte was extracted.
C. count becomes 2; the partial record is discarded and gcount() becomes zero.
D. count becomes 3; read() zero-fills the missing half of the final record.

60 While constructing a derived object, its base subobject and member m1 are constructed successfully, but member m2's constructor throws. Which destruction behavior is guaranteed?

Manager functions: constructors and destructor Hard
A. m1 and the base are destroyed in that order; neither m2 nor the derived object is destroyed.
B. m2, m1, and the base are destroyed, but the derived destructor body is not executed.
C. The derived object, m2, m1, and the base are all destroyed in reverse declaration order.
D. Only the base is destroyed because member destruction begins after the constructor body starts.