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. open()
B. write()
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. ignore()
B. clear()
C. flush()
D. close()

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

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

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

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

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

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

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. put()
D. get()

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

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

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

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

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

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

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

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

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

Classes and file operations Easy
A. fstream
B. ofstream
C. ifstream
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. enum
C. class
D. union

14 When is a constructor normally called for an object?

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

15 What is a default constructor?

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

16 What does a default argument in a constructor provide?

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

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

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

18 What distinguishes a parameterized constructor from a default constructor?

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

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. Period .
B. Semicolon ;
C. Colon :
D. Comma ,

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. if (in.is_open()) in.close();
B. if (in.eof()) in.clear();
C. in.flush(); closes the input file after transferring all buffered input to the program.
D. if (in.good()) in.open();

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::ate
B. ios::out | ios::trunc
C. ios::out | ios::app
D. ios::in | ios::out

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. get() and putback(0)
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. tellg() and seekg(0, ios::beg)

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. getline(fin, age);
B. getline(fin >> ws, name);
C. fin.get(name);
D. fin << 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. Close and reopen the file before each record.
C. Read records sequentially from the beginning.
D. Use getline() until record 700 is reached.

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 << reinterpret_cast<const char*>(&value);
C. out.put(static_cast<char*>(value));
D. out.write(reinterpret_cast<const char*>(&value), sizeof(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. friend istream& operator>>(istream& in, Student& s);
B. friend Student operator>>(Student s, istream in);
C. Make every data member public and let the stream access and modify each field without an extraction operator.
D. istream& operator>>(istream& in);

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.good()) { process(r); in.read(reinterpret_cast<char*>(&r), sizeof(r)); }
B. while (!in.eof()) { in.read(reinterpret_cast<char*>(&r), sizeof(r)); process(r); }
C. while (in.read(reinterpret_cast<char*>(&r), sizeof(r))) process(r);
D. do { process(r); } while (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. Base constructor, members in declaration order, constructor body
B. Members in initializer-list order, constructor body, base constructor
C. Base constructor, constructor body, members in reverse declaration order
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 protected constructor
B. A destructor that explicitly identifies and calls every possible derived-class destructor before releasing the base portion
C. A static destructor
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;
C. Meter m = { };
D. Meter m = 5;

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. Transfer the pointer from the source object and modify the supposedly constant source so that it no longer owns the allocation.
B. Copy only the pointer address.
C. Allocate a new array and copy its elements.
D. Set both pointers to nullptr.

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. New content is appended to its end.
B. The file becomes read-only.
C. Its existing contents are discarded.
D. The file pointer starts at the end while all existing content remains available for later random-access updates.

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.clear(); in.seekg(0, ios::beg);
C. in.eof(); in.open();
D. in.flush(); in.tellg();

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.seekp(k * sizeof(Record), ios::beg);
B. file.tellp(k * sizeof(Record));
C. file.seekg(k + sizeof(Record), ios::beg);
D. file.seekp(k, ios::end);

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

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

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

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

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 true; 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 false; both files contain X after f.close().
D. failed is false; A.bin contains X, while B.bin remains empty.

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. 12 bytes, because ate preserves the file and every write is forced to its end.
B. 2 bytes, because ofstream adds out, which truncates the file before the initial end seek.
C. 12 bytes, because binary implicitly adds app when combined with ate.
D. 10 bytes, because the first two bytes are overwritten after opening at the end.

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

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 = 0
B. a = 10, b = 20, and c = -1
C. a = 10, b = 20, and c = 30
D. a = 10, b = -1, and c = 30

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) + static_cast<std::streamoff>(k) * S
C. static_cast<std::streamoff>(H) + static_cast<std::streamoff>(k + 1) * S
D. static_cast<std::streamoff>(H - 1) + static_cast<std::streamoff>(k) * 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 converts the characters to implementation-defined binary codes that formatted input cannot decode.
D. It stores characters correctly but omits the null terminator required by std::string reconstruction.

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. Read sizeof(Class) bytes directly into an object created with its ordinary default constructor.
C. Allocate uninitialized storage, copy the file bytes into it, and treat the storage as a live object.
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. Padding, alignment, byte order, and type representation may differ between implementations.
C. Binary streams automatically compress padding bytes and therefore change the structure's size.
D. A structure's member declaration order may be rearranged independently each time it is written.

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

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

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

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

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

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

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

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

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 default-initialized and then assigned after x, so both members are valid.
B. y is initialized before x, so evaluating x + 1 reads an indeterminate value.
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. ZABCDE, because app inserts output at the requested position.
B. ZBCDE, because seekp(0) overrides the initial append position.
C. ABCDE, because combining in, out, and app disables output.
D. ABCDEZ, because app forces each output operation to the end.

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.read(buffer, size); io.clear(); io.seekp(0, std::ios::end);
B. io.clear(); io.read(buffer, size); io.seekg(0, std::ios::beg);
C. io.seekp(0, std::ios::beg); io.read(buffer, size); io.flush();
D. io.flush(); io.seekg(0, std::ios::beg); io.read(buffer, size);

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 the get position to i*S, read, then seek the put position to i*S and write.
B. Seek both positions to (i+1)*S, read the record, and write it at the same position.
C. Read sequentially through record i, modify it, and write immediately without repositioning.
D. Seek the put position to i*S, read, then seek the get position to i*S and write.

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 record is discarded and gcount() becomes zero.
B. count becomes 3; read() zero-fills the missing half of the final record.
C. count becomes 2; the partial read fails, and gcount() reports half a record.
D. count becomes 3; the loop body runs whenever at least one byte was extracted.

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. Only the base is destroyed because member destruction begins after the constructor body starts.
B. The derived object, m2, m1, and the base are all destroyed in reverse declaration order.
C. m2, m1, and the base are destroyed, but the derived destructor body is not executed.
D. m1 and the base are destroyed in that order; neither m2 nor the derived object is destroyed.